﻿'/**********************************************************************
'/// <summary>
'// Name of File     :   DataHub.vb
'// Author           :   Sukhminder Singh
'// Create date      :   2nd Feb 2011
'/// </summary>
'************************************************************************/
Imports Crystal.CLL
Imports CrystalDataHub.BLL
Imports Infragistics.Win.UltraWinGrid
Imports CrystalDataHub.BLL.DataHubManager
Imports Infragistics.Win
Imports Crystal.CustomControls
Imports Infragistics.Win.UltraWinGrid.ExcelExport
Imports Infragistics.Documents.Excel
Imports System.Text
Imports CrystalCommon.BLL
Imports CrystalDataHub.BLL.CrystalDataHub.BLL
Imports System.Text.RegularExpressions
Imports CrystalDatabaseManagement.View
Imports Infragistics.Win.UltraWinToolTip
Imports CrystalDataHub.BLL.DataHub.BusinessObject
Imports System.IO
Imports System.Xml.Serialization
Imports Infragistics.Win.UltraWinDataSource
Imports LumenWorks.Framework.IO.Csv
Imports System.Threading
Imports Crystal.Common.Model

Public Class DataHub
    Inherits BaseForm

#Region "Fields"

    Public menmScreenType As DataHubScreenType
    Public mintClientID As Integer
    Public mintProjectID As Integer
    Public mstrClientName As String
    Public mstrProjectName As String
    Public mintPreviousProjectID As Integer
    Public mstrPreviousProjectName As String
    Public mstrDeliveryListingToSort As String

    Private mstrScreenName As String = "Data Hub"
    Private mclsDataHubManager As New DataHubManager
    Private mstrDENotesDefaultText As String = "DE Notes:" & Environment.NewLine
    Private mstrFLNotesDefaultText As String = "FL Notes:" & Environment.NewLine
    'Private marrSysColNames() As String = {"IsInvestor", "InvStatusCode", "IsMasterDB", "InvestorID", "InvestorName", "FundName", "MInvestorTypeID", "LinkID", "IsManaged", "FundID", "IsCutRow", "UserID", "ProjectID"}
    Private mstSysColumns As List(Of String) = Nothing

    'Private marrSysColNames() As String = {"IsInvestor", "InvStatusCode", "IsMasterDB", "InvestorID", "InvestorName", "FundName", "MInvestorTypeID", "LinkID", "IsManaged", "FundID", "IsCutRow", "UserID", "ProjectID", "RowNumber", "DenseRank", "FundDenseRank"}
    Private marrDefaultHiddenColNames() As String = {"ID", "Status", "Head Investor", "Parent", "Activist", "Region"}
    Private mstESourceType As List(Of String) = {SourceTypeCode.PBC.ToString, SourceTypeCode.EBL.ToString, SourceTypeCode.RGT.ToString, SourceTypeCode.EPB.ToString}.ToList
    'Private marrSysColNamesToRemove() As String = {"PositionsForSort", "DSID", "DSFRMID", "DSSOFID", "DSSDateID", "DSPReportDateID", "DSPSourceID", "DSCSSourceID", _
    '                                               "DSGSourceID", "PPID", "IsDSInvestor", "IsFRMInvestor", "IsSOFInvestor", "IsSDateInvestor", "IsPReportDateInvestor", _
    '                                               "IsPSourceInvestor", "IsCSSourceInvestor", "IsGSourceInvestor", "IsPPInvestor", "PPFRMID", "IsPPFRMInvestor", _
    '                                               "PPSOFID", "IsPPSOFInvestor"}

    Private mdtDEAssociatedData As DataTable
    Private mdtFLAssociatedData As DataTable
    Private marrSysColNamesToRemove() As String = {}
    Private mstExcludedFromChooser As List(Of String)
    Private mstrFundPrefixSpaces As String = "     "
    Private mstrNDValue As String = "ND"
    Private mstrFLCurrentListingPrefix As String = "Current "
    Private mstrFLSuggestedFinalListingPrefix As String = "Suggested Final "

    Private mclrColHeadBackColor As Color
    Private mclrDelAndExtnct As Color
    Private mclrDelAndExtnctForDataSource As Color
    Private mclrGridSelCellBackColor As Color
    Private mclrGridInvBackColor As Color
    Private mclrGridFundBackColor As Color
    Private mclrGridForeColor As Color

    Private mintDataSourcesCount As Integer

    Private mstCurrentDataSources As New List(Of CurrentDataSources)
    Private mstPreviousDataSources As New List(Of PreviousDataSources)
    Private mstPreviousProjects As New List(Of PreviousProjects)
    Private mstListingInformation As New List(Of ListingInformation)
    Private mstAttributeSet1 As IList(Of String) = Nothing
    Private mstAttributeSet2 As IList(Of String) = Nothing
    Private mstDataSourceParentGroupPositionCol As New List(Of String)
    Private mstDataSourceParentGroupDateCol As New List(Of String)
    Private mstAllPreviousListings As New List(Of String)


    Private mintParentIndex As Int16
    Private mintLinkIDColIndex As Int16
    Private mintFundNameColIndex As Int16
    Private mintNameColIndex As Int16
    Private mintIsManagedColIndex As Int16
    Private mintTypeColIndex As Integer

    Private mstDataSourceChanges As New List(Of DataSourceChanges)
    Private mstPreviousProjectChanges As New List(Of FLPositionChanges)
    Private mstLinkingChanges As New List(Of LinkingChanges)
    Private mstFLChanges As New List(Of FLPositionChanges)

    Private marrCutRows As New List(Of UltraGridRow)

    Private marrToplineNot0ExcludeDataSources() As String = {DataSourceCode.DDALCOT.ToString}

    Private marrToplineNot0() As String = {SourceTypeCode.DDI.ToString}
    Private mstEditableDataSourceNameCols As List(Of String)
    'Private mstSOFCols As List(Of String)

    Private mstAllDataSourceNameCols As List(Of String)
    Private mstAllDataSourceDateCols As List(Of String)

    Private mstPublicSourcesCols As List(Of String)
    Private mstPublicFilingDateCols As List(Of String)
    Private mstResearchSourceCols As List(Of String)
    Private mstResearchDateCols As List(Of String)

    Private marrPreviousDataSourceNameCols(0) As String
    Private marrPreviousSourceDateCols(0) As String

    Private marrPreviousProjects(0) As String

    Private marrAllVisibleSourceNameCols(0) As String
    Private marrAllColumnsDataHub(0) As String
    Private mstrCollapsedCategories As String = "UDI,RBC,PFL"

    Private mdtAppendCurrentDataSource As DataTable
    Private mstrRightClickColName As String = ""

    Private mstrInvSearchText As String = ""
    Private mstrFundSearchText As String = ""
    Private mblnAnyChangesInLastProject As Boolean = False
    Private mblnHasMasterSearchRecords As Boolean = False
    Private mblnIsFromMasterSearch As Boolean = False
    Private mblnIsCutOperationInProgress As Boolean = False
    Private mintLastTranversedInvestorID As Integer
    Private mintLastTranversedInvIndex As Integer

    Private menmSearchTextTypes As SearchTextTypes
    Private menmSearchResultType As SearchResultType
    Private menmSearchType As SearchTypes
    Private menmSortingOn As SortingOn
    Private menmDELoadUpType As DELoadUpType

    Private mthdThread As Thread
    Private marrVisibleColumnsFL(0) As String

    Private mdicShortCut As New Dictionary(Of String, String)

    Delegate Sub ChangeColorToNormal(ByRef ldtCurrentData As DataTable)
    Delegate Sub RecallDataChange(ByRef lblnShouldReSort As Boolean)
    Delegate Sub InvestorFundDetails(ByVal lstRecallAddResults As IList(Of InvestorFundResults), ByVal pblnIsFromMaster As Boolean, ByVal lintRowNumber As Integer, ByRef ldtCurrentData As DataTable)
    Delegate Sub AccessControl(ByVal penmSearchResultType As SearchResultType)
    Delegate Sub PrepareSearch(ByVal txtSearch As TextBox, ByVal pblnIsFromInvestor As Boolean, ByVal lstMAInvestors As IList(Of MAInvestors), ByVal lstChangeLogData As IList(Of LinkingDetails))
    Delegate Sub SetInvestorFund(ByVal lstRecallDataChanges As List(Of RecallData), ByVal lstRecallAddResults As IList(Of InvestorFundResults), ByVal pblnIsFromMaster As Boolean, ByRef ldtCurrentData As DataTable)
    Delegate Sub Sort(ByVal pstrDeliveryListing As String)
    Delegate Sub SetControlValues(ByVal pblnValue As Boolean)

    Private mintColumnIndex As Integer = -1
    Private mint32RowCount As Int32
    Private mstrInvestorNameSearch As String
    Private mblnColumnListStatus As Boolean = False
    Private mblsSourceData As Boolean = False

    Enum SortingOn
        Ascending = 1
        Positions = 2
    End Enum

    Enum InvestorPositionSources
        OnCellChange = 1
        RevertToSumOfFunds = 2
    End Enum

    Enum RecallChangesCaller
        OnLoad = 1
        ColumnList = 2
        ReEnableDataHub = 3
    End Enum

    Enum SearchTypes
        OnlyInvestor = 1
        OnlyFund = 2
        Both = 3
        MandA = 4
        ChangeLog = 5
    End Enum

    Enum SearchTextTypes
        SingleText = 1
        DoubleText = 2
        Blank = 3
    End Enum

    Enum SearchResultType
        All = 1
        CustomSearch = 2
        ColumnFilter = 3
    End Enum

    Enum DELoadUpType
        Database = 1
        Snapshot = 2
        DefaultLoad = 3
        CallDatabase = 4
    End Enum

    Enum FixedStateColumnType
        None = 1
        SourceName = 2
        SourceDate = 3
        PublicFilingDate = 4
        PublicSource = 5
        ResearchSource = 6
    End Enum

    Private mblnCheckNewRow As Boolean = False
    Private mdtNewRowData As DataTable
    Private mlstFundInvestor As List(Of Crystal.Common.Model.AddNewInvestor)
#End Region

#Region "On Load"

    Private Sub DataHub_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        CallOnLoad()
    End Sub

    ''' <summary>
    ''' To load the onload functions
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub CallOnLoad()
        SetOnLoadControls()
        LoadGridData(DELoadUpType.DefaultLoad)
        InitializeChangeTrackTable()
    End Sub

    ''' <summary>
    ''' To set the controls on load
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub SetOnLoadControls()
        Dim Values As Integer()
        Me.WindowState = FormWindowState.Maximized
        Me.Text = "Crystal - " + mstrClientName + " - " + mstrProjectName + " - " + TitleManager.GetTitle("DataHub")
        If menmScreenType = DataHubScreenType.DataEntry Then
            Me.Text += " - Data Entry"
        Else
            Me.Text += " - Finalise Listing"
        End If
        SetDefaulSearchText(txtInvestor)
        SetDefaulSearchText(txtFund)

        If menmScreenType = DataHubScreenType.DataEntry Then
            txtFLNotes.Enabled = False
            rdbCustomSearch.Checked = True
        Else
            rdbRegularSearch.Checked = True
            btnLoadFromDB.Enabled = False
        End If
        btnReview.Enabled = False
        btnAutoSave.Enabled = False

        rdInvContains.Checked = True
        rdFundContains.Checked = True
        rdAll.Checked = True
        rdbDECurrentNotes.Checked = True
        rdbFLCurrentNotes.Checked = True
        txtDENotes.Text = mstrDENotesDefaultText
        txtFLNotes.Text = mstrFLNotesDefaultText
        cColLockMenu.Items("mnuLockDelete").Enabled = False
        cColUnlockMenu.Items("mnuEdit").Visible = False

        btnReview.Enabled = False
        btnLoadFromDB.Enabled = True

        spcDataHub.Panel2Collapsed = True
        lnkDEFinaliseListNotes.Select()
        Values = New Integer(2) {}

        If CommonCustomControls.IsValidString(StyleManager.GetStyle("GridColHeadBackColor"), Values) Then
            mclrColHeadBackColor = Color.FromArgb(Values(0), Values(1), Values(2))
        End If

        If CommonCustomControls.IsValidString(StyleManager.GetStyle("EDS_DeleteAndExtinctBackColor"), Values) Then
            mclrDelAndExtnct = Color.FromArgb(Values(0), Values(1), Values(2))
        End If

        If CommonCustomControls.IsValidString(StyleManager.GetStyle("DH_DeleteAndExtinctForDataSourceBackColor"), Values) Then
            mclrDelAndExtnctForDataSource = Color.FromArgb(Values(0), Values(1), Values(2))
        End If

        If CommonCustomControls.IsValidString(StyleManager.GetStyle("GridSelCellBackColor"), Values) Then
            mclrGridSelCellBackColor = Color.FromArgb(Values(0), Values(1), Values(2))
        End If

        If CommonCustomControls.IsValidString(StyleManager.GetStyle("DH_GridInv_BackColor"), Values) Then
            mclrGridInvBackColor = Color.FromArgb(Values(0), Values(1), Values(2))
        End If

        If CommonCustomControls.IsValidString(StyleManager.GetStyle("GridNonSelAlternateRowBackColor"), Values) Then
            mclrGridFundBackColor = Color.FromArgb(Values(0), Values(1), Values(2))
        End If

        If CommonCustomControls.IsValidString(StyleManager.GetStyle("GridNonSelRowForeColor"), Values) Then
            mclrGridForeColor = Color.FromArgb(Values(0), Values(1), Values(2))
        End If
        grdData.DisplayLayout.Override.FixedRowIndicator = FixedRowIndicator.None
        grdData.DisplayLayout.UseFixedHeaders = True
        grdData.DisplayLayout.Override.RowSelectorWidth = 10
    End Sub

    ''' <summary>
    ''' To set the grid related properties
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub SetGridProperties()
        'To autoresize the Name column as per the visible rows only.
        grdData.Rows.Band.Columns("Name").PerformAutoResize(PerformAutoSizeType.VisibleRows)
        If menmScreenType = DataHubScreenType.FinalizeList Then
            For Each lobjListingInformation As ListingInformation In mstListingInformation
                If grdData.Rows.Band.Columns.Exists(mstrPreviousProjectName + " " + lobjListingInformation.ListingName) Then
                    grdData.Rows.Band.Columns(mstrPreviousProjectName + " " + lobjListingInformation.ListingName).CellAppearance.BackColor = grdData.DisplayLayout.Appearances("MostRecentLastProject").BackColor
                End If
                grdData.Rows.Band.Columns(mstrCurrentListingColPrefix + lobjListingInformation.ListingName).CellAppearance.BackColor = grdData.DisplayLayout.Appearances("VisiblePosition").BackColor
            Next
        End If
    End Sub

    ''' <summary>
    ''' To get the grid's data's columns' index
    ''' </summary>
    ''' <param name="pdtData"></param>
    ''' <remarks></remarks>
    Private Sub GetGridColumnIndex(ByVal pdtData As DataTable)
        mintParentIndex = pdtData.Columns("Parent").Ordinal
        mintLinkIDColIndex = pdtData.Columns("LinkID").Ordinal
        mintFundNameColIndex = pdtData.Columns("FundName").Ordinal
        mintNameColIndex = pdtData.Columns("Name").Ordinal
        mintIsManagedColIndex = pdtData.Columns("IsManaged").Ordinal
        mintTypeColIndex = pdtData.Columns("Type").Ordinal
    End Sub

#End Region

#Region "Events"

#Region "Form Events"

    ''' <summary>
    ''' To set the location of the Notes and other controls down the screen.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub DataHub_Resize(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Resize
        If Me.WindowState = FormWindowState.Maximized Then
            spcDataHub.SplitterDistance = 585
        ElseIf Me.WindowState = FormWindowState.Normal Then
            spcDataHub.SplitterDistance = 273
        End If
        txtDENotes.Size = New Size(Me.Size.Width / 2 - 40, txtDENotes.Height)
        pnlDENotes.Location = New Point(txtDENotes.Width - pnlDENotes.Width + 13, pnlDENotes.Location.Y)

        txtFLNotes.Location = New Point(txtDENotes.Location.X + txtDENotes.Width + 60, txtFLNotes.Location.Y)
        txtFLNotes.Size = New Size(Me.Size.Width / 2 - 40, txtFLNotes.Height)

        btnCollapse.Location = New Point(Me.Width / 2 - btnCollapse.Width / 2, btnCollapse.Location.Y)

        Dim lintAllDecisionLinksLength = lnkGeneralSource.Width + lnkBanklistSource.Width + lnkInvestorLinks.Width + lnkCurrentPreviousSource.Width + lnkSimilarNamed.Width + lnkDEFinaliseListNotes.Width
        Dim lintTotalWidthForDistance = pnlDecisionAidBox.Width - lintAllDecisionLinksLength
        Dim lintPerWidthForDistance = lintTotalWidthForDistance / 5
        lnkBanklistSource.Location = New Point(lnkGeneralSource.Location.X + lnkGeneralSource.Width + lintPerWidthForDistance, lnkBanklistSource.Location.Y)
        lnkInvestorLinks.Location = New Point(lnkBanklistSource.Location.X + lnkBanklistSource.Width + lintPerWidthForDistance, lnkInvestorLinks.Location.Y)
        lnkCurrentPreviousSource.Location = New Point(lnkInvestorLinks.Location.X + lnkInvestorLinks.Width + lintPerWidthForDistance, lnkCurrentPreviousSource.Location.Y)
        lnkSimilarNamed.Location = New Point(lnkCurrentPreviousSource.Location.X + lnkCurrentPreviousSource.Width + lintPerWidthForDistance, lnkSimilarNamed.Location.Y)
        lnkDEFinaliseListNotes.Location = New Point(lnkSimilarNamed.Location.X + lnkSimilarNamed.Width + lintPerWidthForDistance - 10, lnkDEFinaliseListNotes.Location.Y)
    End Sub

    ''' <summary>
    ''' Set the screen status for the current project
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub ImporteSource_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Dim ldrSaveExit As DialogResult
        Dim lblnCanCreateSnapshot As Boolean = True
        Dim lblnCanCallUnLock As Boolean = False
        Dim lblnCanGoAhead As Boolean
        Try
            'If there are any change then ask the user if he wants to save
            If mstDataSourceChanges.Count > 0 OrElse mstPreviousProjectChanges.Count > 0 OrElse mstLinkingChanges.Count > 0 Then
                'Confirm from the user
                ldrSaveExit = MessageBox.Show(MessageManager.GetMessage(DBResult.SAVE_EXIT_CNFRM.ToString), MessageManager.GetMessage("CRYSTAL"), MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
                If ldrSaveExit = DialogResult.Yes Then
                    'To unlock the locked data sources
                    lblnCanGoAhead = True
                    CallUnlockFunctionality(False, False, lblnCanGoAhead)
                    If lblnCanGoAhead = False Then e.Cancel = True
                ElseIf ldrSaveExit = DialogResult.Cancel Then
                    lblnCanCreateSnapshot = False
                    e.Cancel = True
                ElseIf ldrSaveExit = DialogResult.No Then
                    'To unlock the locked data sources
                    CType(grdData.DataSource, DataTable).RejectChanges()
                    CallUnlockFunctionality(False, True, True)
                End If
            ElseIf menmScreenType = DataHubScreenType.DataEntry Then
                'Check if there is any locked column
                For Each lobjCurrentDataSource As CurrentDataSources In mstCurrentDataSources
                    If lobjCurrentDataSource.AccessStatus = SourceAccessbility.Locked.ToString Then
                        lblnCanCallUnLock = True
                        Exit For
                    End If
                Next
                'To unlock the locked data sources
                If lblnCanCallUnLock Then
                    CallUnlockFunctionality(False, True, True)
                End If
            End If

            'lblnCanCreateSnapshot = False
            'Check if a snapshot can be created
            If lblnCanCreateSnapshot Then
                'SaveDataInText()
                'Set the Data Entry screen status of the project to false
                ManageScreenStatus(0, mintProjectID, CommonCLL.UserID, False, False, False)
                If grdData.DataSource IsNot Nothing Then
                    If grdData.Rows.Count > 0 Then
                        'If the current user is the last user to leave, then save the snapshot
                        If mclsDataHubManager.GetDEScreenStatus(mintProjectID) = False Then
                            'Clear all the filters
                            If grdData.Rows.Band.ColumnFilters.Count > 0 Then
                                grdData.Rows.Band.ColumnFilters.ClearAllFilters()
                                'Change the grid's rows backcolor to normal, if there are any non-project db rows from the previous search
                                ChangeRowColorBackToNormal(grdData.DataSource)
                            End If
                            SaveSnapshotInText()
                            'SaveSnapshot()
                        End If
                    End If
                End If
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            If ldrSaveExit <> DialogResult.Cancel Then
                Me.Dispose()
            End If
            ldrSaveExit = Nothing
        End Try
    End Sub
#End Region

#Region "Grid Events"

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub grdData_AfterCellActivate(ByVal sender As Object, ByVal e As System.EventArgs) Handles grdData.AfterCellActivate
        Dim lobjCurrentCol As CurrentDataSources = Nothing
        Dim lstrDataSourceColName As String = ""
        Try
            If mstEditableDataSourceNameCols.Contains(grdData.ActiveCell.Column.Header.Caption) OrElse mstAllDataSourceDateCols.Contains(grdData.ActiveCell.Column.Header.Caption) OrElse mstResearchSourceCols.Contains(grdData.ActiveCell.Column.Header.Caption) Then
                'If some positions are changed after a Cut operation, then Cancel out the cut operation
                If mstEditableDataSourceNameCols.Contains(grdData.ActiveCell.Column.Header.Caption) Then
                    lstrDataSourceColName = grdData.ActiveCell.Column.Header.Caption
                    If HasFormulas(grdData.ActiveCell.Row.GetCellValue(lstrDataSourceColName).ToString) Then Exit Sub
                ElseIf mstAllDataSourceDateCols.Contains(grdData.ActiveCell.Column.Header.Caption) Then
                    lstrDataSourceColName = grdData.ActiveCell.Column.Header.Caption.Substring(0, grdData.ActiveCell.Column.Header.Caption.Length - mstrSourceDateColSuffix.Length)
                ElseIf mstResearchSourceCols.Contains(grdData.ActiveCell.Column.Header.Caption) Then
                    lstrDataSourceColName = grdData.ActiveCell.Column.Header.Caption.Substring(0, grdData.ActiveCell.Column.Header.Caption.Length - mstrSourceColSuffix.Length)
                End If
                If mblnIsCutOperationInProgress = False Then
                    CancelOutCutOperation()
                End If
                'ldrDataSource = mdtCurrentDataSources.Rows.Find(lstrDataSourceColName)
                lobjCurrentCol = mstCurrentDataSources.Find(Function(p) p.SourceName = lstrDataSourceColName)
                If lobjCurrentCol Is Nothing Then Exit Sub
                'If the current data source is locked 
                If (lobjCurrentCol.AccessStatus = SourceAccessbility.Locked.ToString OrElse menmScreenType = DataHubScreenType.FinalizeList) AndAlso (mstResearchDateCols.Contains(grdData.ActiveCell.Column.Header.Caption) OrElse mstResearchSourceCols.Contains(grdData.ActiveCell.Column.Header.Caption)) Then
                    If grdData.ActiveRow.GetCellValue(lobjCurrentCol.SourceName).Equals("") = False Then
                        If mblsSourceData = False Then
                            ShowSourceData(grdData.ActiveCell, lobjCurrentCol)
                        Else
                            mblsSourceData = False
                        End If
                    End If
                Else
                    If lobjCurrentCol.AccessStatus <> SourceAccessbility.Locked.ToString AndAlso menmScreenType = DataHubScreenType.DataEntry Then
                        grdData.ActiveCell.Activation = Activation.ActivateOnly
                    End If
                End If
                ''''''''''''Starts: Temporarily Commented'''''''''''''''''''''''
                ' ''Check if the current source is Research and if the value is not nothing, then user has to give specify date and the Source
                'If grdData.Selected.Cells.Count > 1 Then Exit Sub
                'ShowSourceData(grdData.ActiveCell, lobjCurrentCol)
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            lobjCurrentCol = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="lcell"></param>
    ''' <param name="lobjCurrentCol"></param>
    ''' <remarks></remarks>
    Private Sub ShowSourceData(ByRef lcell As UltraGridCell, ByVal lobjCurrentCol As CurrentDataSources)
        If lcell.Column.Header.Caption.EndsWith(mstrSourceDateColSuffix) Then
            If lcell.Band.Columns.Exists(lcell.Column.Header.Caption.Replace(mstrSourceDateColSuffix, "")) Then
                If lcell.Row.GetCellValue(lcell.Column.Header.Caption.Replace(mstrSourceDateColSuffix, "")).ToString <> String.Empty Then
                    ShowSourceDataDialog(lcell)
                End If
            End If
        End If
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="lcell"></param>
    ''' <remarks></remarks>
    Private Sub ShowSourceDataDialog(ByRef lcell As UltraGridCell)
        Dim lSourceData As New SourceData
        Try
            If lcell.Value.ToString <> String.Empty Then
                lSourceData.mdateSourceDate = lcell.Value
            End If
            If lcell.Band.Columns.Exists(lcell.Column.Header.Caption.Replace(mstrSourceDateColSuffix, mstrClientSpecificSourceColSuffix)) Then
                lSourceData.mstrClientSpecificSource = lcell.Row.GetCellValue(lcell.Column.Header.Caption.Replace(mstrSourceDateColSuffix, mstrClientSpecificSourceColSuffix)).ToString
            End If
            If lcell.Band.Columns.Exists(lcell.Column.Header.Caption.Replace(mstrSourceDateColSuffix, mstrGenericSourceColSuffix)) Then
                lSourceData.mstrGenericSource = lcell.Row.GetCellValue(lcell.Column.Header.Caption.Replace(mstrSourceDateColSuffix, mstrGenericSourceColSuffix)).ToString
            End If
            lSourceData.ShowDialog()
            If lSourceData.mblnSaved Then
                lcell.Value = lSourceData.mdateSourceDate
                If lcell.Band.Columns.Exists(lcell.Column.Header.Caption.Replace(mstrSourceDateColSuffix, mstrClientSpecificSourceColSuffix)) Then
                    lcell.Row.Cells(lcell.Column.Header.Caption.Replace(mstrSourceDateColSuffix, mstrClientSpecificSourceColSuffix)).Value = lSourceData.mstrClientSpecificSource
                End If
                If lcell.Band.Columns.Exists(lcell.Column.Header.Caption.Replace(mstrSourceDateColSuffix, mstrGenericSourceColSuffix)) Then
                    lcell.Row.Cells(lcell.Column.Header.Caption.Replace(mstrSourceDateColSuffix, mstrGenericSourceColSuffix)).Value = lSourceData.mstrGenericSource
                    'lSourceData.mstrGenericSource = lcell.Row.GetCellValue(lcell.Column.Header.Caption + mstrGenericSourceColSuffix).ToString
                End If
                If lSourceData.mstrClientSpecificSource <> String.Empty Then
                    lcell.Row.Cells(lcell.Column.Header.Caption.Replace(mstrSourceDateColSuffix, mstrSourceColSuffix)).Value = lSourceData.mstrClientSpecificSource
                Else
                    lcell.Row.Cells(lcell.Column.Header.Caption.Replace(mstrSourceDateColSuffix, mstrSourceColSuffix)).Value = lSourceData.mstrGenericSource
                End If
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            lSourceData = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' If multiple rows are selected,Disable the mnuAddNewInvestor and mnuAddNewFund. 
    ''' Else enable the mnuAddNewInvestor and mnuAddNewFund. 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub grdData_AfterSelectChange(ByVal sender As Object, ByVal e As Infragistics.Win.UltraWinGrid.AfterSelectChangeEventArgs) Handles grdData.AfterSelectChange
        Dim lintActiveRowIndex As Integer
        Dim lintRowCounter As Integer
        Dim lstrCellValue As String = String.Empty
        Dim lintActiveColIndex As Integer
        Dim sumPositionValues As Int64 = 0
        Dim lugcSelectedCell As UltraGridCell = Nothing
        Dim lstrFormula As String = String.Empty
        Try
            If grdData.Selected.Cells.Count = 1 Then
                txtWhiteBar.Text = String.Empty
                lugcSelectedCell = grdData.Selected.Cells(0)
                'If clicked cell formaula exist than display the formula else show the text.
                'If lugcSelectedCell.Row.GetCellValue("LinkID") = 0 Then
                lstrFormula = GetFormula(grdData.ActiveCell.Row.GetCellValue("InvestorID"), grdData.ActiveCell.Row.GetCellValue("FundID"), grdData.ActiveCell.Row.GetCellValue("LinkID"), lugcSelectedCell.Column.Header.Caption, False)
                'ElseIf lugcSelectedCell.Row.GetCellValue("LinkID") <> 0 Then
                '  txtWhiteBar.Text = lugcSelectedCell.Value.ToString.Trim
                '   Exit Sub
                'End If
                If lstrFormula <> String.Empty Then
                    txtWhiteBar.Text = lstrFormula
                Else
                    If lugcSelectedCell.Row.GetCellValue("LinkID") = 0 Then
                        'Check if mstrSOFColPrefix  of column exist.
                        If CheckSumOfFunds(grdData.ActiveCell.Row.GetCellValue("InvestorID"), lugcSelectedCell.Column.Header.Caption, False, False) = True Then
                            lintActiveColIndex = grdData.ActiveCell.Column.Index
                            lintActiveRowIndex = grdData.ActiveCell.Row.Index
                            'Index + 1 because the selected row / cell index start from 0.
                            lintRowCounter = lintActiveRowIndex + 1
                            'Start a loop to make a string like '34+34+53'
                            If lintRowCounter < grdData.Rows.Count Then
                                While lintRowCounter < grdData.Rows.Count And grdData.Rows(lintRowCounter).GetCellValue("LinkID") <> 0
                                    If grdData.Rows(lintRowCounter).GetCellValue(grdData.ActiveCell.Column).ToString.Equals("") Then
                                        lintRowCounter += 1
                                        If lintRowCounter = grdData.Rows.Count Then Exit While
                                        Continue While
                                    End If
                                    If lstrCellValue = String.Empty Then
                                        lstrCellValue += grdData.Rows(lintRowCounter).GetCellValue(grdData.ActiveCell.Column).ToString.Trim
                                    Else
                                        lstrCellValue += "+" + grdData.Rows(lintRowCounter).GetCellValue(grdData.ActiveCell.Column).ToString.Trim
                                    End If
                                    lintRowCounter += 1
                                    If lintRowCounter = grdData.Rows.Count Then Exit While
                                End While
                            End If
                            txtWhiteBar.Text = lstrCellValue.Trim
                        Else
                            txtWhiteBar.Text = grdData.ActiveCell.Row.GetCellValue(grdData.ActiveCell.Column).ToString.Trim
                        End If
                    Else
                        txtWhiteBar.Text = grdData.ActiveCell.Row.GetCellValue(grdData.ActiveCell.Column).ToString.Trim
                    End If
                End If
            Else
                'If multiple cells are selected.
                If grdData.Selected.Cells.Count > 1 Then
                    'If cell selectionstart from any of this array marrAllDataSourceNameCols , marrPreviousDataSourceNameCols Or marrPreviousProjects 
                    'Than Sum the value of cells.
                    lugcSelectedCell = grdData.Selected.Cells(0)
                    If mstAllDataSourceNameCols.Contains(lugcSelectedCell.Column.Header.Caption) Or marrPreviousDataSourceNameCols.Contains(lugcSelectedCell.Column.Header.Caption) _
                        Or marrPreviousProjects.Contains(lugcSelectedCell.Column.Header.Caption) Or lugcSelectedCell.Column.Header.Caption.StartsWith(mstrCurrentListingColPrefix) Then
                        For i As Integer = 0 To grdData.Selected.Cells.Count - 1
                            lugcSelectedCell = grdData.Selected.Cells(i)
                            If mstAllDataSourceNameCols.Contains(lugcSelectedCell.Column.Header.Caption) Or marrPreviousDataSourceNameCols.Contains(lugcSelectedCell.Column.Header.Caption) _
                                Or marrPreviousProjects.Contains(lugcSelectedCell.Column.Header.Caption) Or lugcSelectedCell.Column.Header.Caption.StartsWith(mstrCurrentListingColPrefix) Then
                                If lugcSelectedCell.Row.GetCellValue(lugcSelectedCell.Column.Header.Caption).ToString.Equals("") = False Then
                                    sumPositionValues = sumPositionValues + Convert.ToInt64(lugcSelectedCell.Row.GetCellValue(lugcSelectedCell.Column.Header.Caption).ToString)
                                End If
                            End If
                        Next
                        txtWhiteBar.Text = sumPositionValues.ToString.Trim
                    Else
                        'Display the value of first selected cell value.
                        txtWhiteBar.Text = lugcSelectedCell.Row.GetCellValue(grdData.Selected.Cells(0).Column).ToString.Trim
                    End If
                End If
            End If
            'Enable/Disable the menucontext on row selection.
            If grdData.Selected.Rows.Count = 1 Then
                mnuAddNewInvestor.Enabled = True
                mnuAddNewFund.Enabled = True
            ElseIf grdData.Selected.Rows.Count > 1 Then
                mnuAddNewInvestor.Enabled = False
                mnuAddNewFund.Enabled = False
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            lugcSelectedCell = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' To recall the changes and update the grid before the selected filter is changed.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub grdData_BeforeRowFilterChanged(ByVal sender As Object, ByVal e As Infragistics.Win.UltraWinGrid.BeforeRowFilterChangedEventArgs) Handles grdData.BeforeRowFilterChanged
        Dim lblnShouldReSort As Boolean = False
        'Recall the data and update the grid
        RecallDataChanges(lblnShouldReSort)
        'If changes are made that requires the resort then call the resort
        If lblnShouldReSort Then
            ConductSorting("")
        End If
    End Sub

    ''' <summary>
    ''' To set the InvestorName visiblity, toggling of radio buttons once the row filter is changed.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub grdData_AfterRowFilterChanged(ByVal sender As Object, ByVal e As Infragistics.Win.UltraWinGrid.AfterRowFilterChangedEventArgs) Handles grdData.AfterRowFilterChanged
        ShowInvestorNameColForColumnFilter()
        If grdData.Rows.GetFilteredOutNonGroupByRows.Count = 0 Then
            menmSearchResultType = SearchResultType.All
        ElseIf menmSearchResultType <> SearchResultType.CustomSearch Then
            menmSearchResultType = SearchResultType.ColumnFilter
        End If
        SetSearchFilterResultText(menmSearchResultType)
        rdbRegularSearch.Checked = True
    End Sub

    ''' <summary>
    ''' To do the grid settings during initialization
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub grdData_InitializeLayout(ByVal sender As Object, ByVal e As Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs) Handles grdData.InitializeLayout
        'Exit Sub
        Dim lIsMasterDBAppereance As Appearance
        Dim lUnlinkedFundAppereance As Appearance
        Dim lMasterDBFundAppereance As Appearance
        Dim lDelAndExtnctAppereance As Appearance
        Dim lDelAndExtnctDataSourceAppereance As Appearance
        Dim lToolTipInfoAppereance As Appearance
        Dim lHasAnyDoubtsAppereance As Appearance
        Dim lColHeadBackColorAppereance As Appearance
        Dim lMandAParentRowAppereance As Appearance
        Dim lGridForeColorAppereance As Appearance
        Dim lGridInvAddedAppereance As Appearance
        Dim lCutRowBackColorAppereance As Appearance
        Dim lCancelCutAppereance As Appearance
        Dim lInvestorRowColorAppereance As Appearance
        Dim lFundRowAppereance As Appearance
        Dim lVisiblePositionAppereance As Appearance
        Dim lMostRecentLastProjectAppearance As Appearance
        Dim lRedBAackColorAppereance As Appearance
        Dim rootband As UltraGridBand = e.Layout.Bands(0)
        Try
            'Hide the column specified in the hidden list
            For Each lstrColName As String In marrDefaultHiddenColNames
                rootband.Columns(lstrColName).Hidden = True
            Next

            For Each lstrColName As String In mstSysColumns
                grdData.Rows.Band.Columns(lstrColName).Hidden = True
            Next

            e.Layout.Override.HeaderClickAction = HeaderClickAction.Select
            e.Layout.Override.AllowMultiCellOperations = AllowMultiCellOperation.All
            e.Layout.SelectionOverlayColor = SystemColors.Highlight
            e.Layout.Override.ActiveAppearancesEnabled = Infragistics.Win.DefaultableBoolean.False
            e.Layout.Override.SelectedAppearancesEnabled = Infragistics.Win.DefaultableBoolean.False
            rootband.Columns("InvestorName").CellAppearance.FontData.Bold = DefaultableBoolean.True

            ''To enable the thousand splitter on all data source positions columns of current project
            For Each lstrColName As String In mstSysColumns
                'If lstrColName.Equals("InvestorName") Then Continue For
                rootband.Columns(lstrColName).CellDisplayStyle = CellDisplayStyle.PlainText
            Next

            'To enable the thousand splitter on all data source positions columns of current project
            For Each lobjCurrentDataSources As CurrentDataSources In mstCurrentDataSources
                rootband.Columns(lobjCurrentDataSources.SourceName).Editor.DataFilter = New ThousandFormatter()
                If menmScreenType = DataHubScreenType.DataEntry Then
                    rootband.Columns(lobjCurrentDataSources.SourceName).CellActivation = Activation.NoEdit
                    If grdData.Rows.Band.Columns.Exists(lobjCurrentDataSources.SourceDate) Then
                        rootband.Columns(lobjCurrentDataSources.SourceDate).CellActivation = Activation.NoEdit
                    End If
                End If
                'If lobjCurrentDataSources.SourceDate.Equals("") = False Then
                '    rootband.Columns(lobjCurrentDataSources.SourceDate).CellActivation = Activation.NoEdit
                'End If
                'If lobjCurrentDataSources.SourceDate.Equals("") = False Then
                '    rootband.Columns(lobjCurrentDataSources.SourceDate).Style = ColumnStyle.Date
                '    'rootband.Columns(lobjCurrentDataSources.SourceDate).Format = "MM/dd/yyyy"
                'End If
            Next

            For Each lstrResearchDateColName As String In mstResearchDateCols
                If rootband.Columns.Exists(lstrResearchDateColName) Then
                    rootband.Columns(lstrResearchDateColName).CellActivation = Activation.NoEdit
                End If
            Next

            ''To enable the thousand splitter on all data source positions columns of previous project
            For Each lobjPreviousDataSources As PreviousDataSources In mstPreviousDataSources
                If grdData.Rows.Band.Columns.Exists(lobjPreviousDataSources.SourceName) Then
                    rootband.Columns(lobjPreviousDataSources.SourceName).CellActivation = Activation.NoEdit
                    rootband.Columns(lobjPreviousDataSources.SourceName).Editor.DataFilter = New ThousandFormatter()
                End If
            Next

            ''To enable the thousand splitter on all listing positions columns of previous project
            For Each lobjPreviousProjects As PreviousProjects In mstPreviousProjects
                If menmScreenType = DataHubScreenType.DataEntry Then
                    rootband.Columns(lobjPreviousProjects.DeliveryListing).CellActivation = Activation.NoEdit
                End If
                rootband.Columns(lobjPreviousProjects.DeliveryListing).Editor.DataFilter = New ThousandFormatter()
            Next

            ''To enable the thousand splitter on Current Listing positions columns
            If menmScreenType = DataHubScreenType.FinalizeList Then
                For Each lobjListingInformation As ListingInformation In mstListingInformation
                    rootband.Columns(lobjListingInformation.CurrentListingName).CellActivation = Activation.AllowEdit
                    rootband.Columns(lobjListingInformation.CurrentListingName).Editor.DataFilter = New ThousandFormatter()

                    If rootband.Columns.Exists(mstrUpdatesColPrefix + lobjListingInformation.ListingName) Then
                        rootband.Columns(mstrUpdatesColPrefix + lobjListingInformation.ListingName).CellActivation = Activation.NoEdit
                        rootband.Columns(mstrUpdatesColPrefix + lobjListingInformation.ListingName + mstrSourceDateColSuffix).CellActivation = Activation.NoEdit
                        rootband.Columns(mstrUpdatesColPrefix + lobjListingInformation.ListingName).Editor.DataFilter = New ThousandFormatter()
                    End If

                    If rootband.Columns.Exists(mstrDDInfoColPrefix + lobjListingInformation.ListingName) Then
                        rootband.Columns(mstrDDInfoColPrefix + lobjListingInformation.ListingName).CellActivation = Activation.NoEdit
                        rootband.Columns(mstrDDInfoColPrefix + lobjListingInformation.ListingName + mstrSourceDateColSuffix).CellActivation = Activation.NoEdit
                        rootband.Columns(mstrDDInfoColPrefix + lobjListingInformation.ListingName).Editor.DataFilter = New ThousandFormatter()
                    End If

                    If rootband.Columns.Exists(mstrRegisterColPrefix + lobjListingInformation.ListingName) Then
                        rootband.Columns(mstrRegisterColPrefix + lobjListingInformation.ListingName).CellActivation = Activation.NoEdit
                        rootband.Columns(mstrRegisterColPrefix + lobjListingInformation.ListingName).Editor.DataFilter = New ThousandFormatter()
                    End If

                    If rootband.Columns.Exists(mstrBanklistColPrefix + lobjListingInformation.ListingName) Then
                        rootband.Columns(mstrBanklistColPrefix + lobjListingInformation.ListingName).CellActivation = Activation.NoEdit
                        rootband.Columns(mstrBanklistColPrefix + lobjListingInformation.ListingName).Editor.DataFilter = New ThousandFormatter()
                    End If
                Next

                'To set the default OR user defined visiblity status of all columns
                SetFLColumnVisibilityStatus()
            Else
                For Each lobjListingInformation As ListingInformation In mstListingInformation
                    If rootband.Columns.Exists(lobjListingInformation.CurrentListingName) Then
                        rootband.Columns(lobjListingInformation.CurrentListingName).Hidden = True
                        rootband.Columns(mstrSuggestedFinalListingColPrefix + lobjListingInformation.ListingName).Hidden = True
                    End If
                Next
                For Each lstrColName As String In mstDataSourceParentGroupPositionCol
                    If rootband.Columns.Exists(lstrColName) Then
                        rootband.Columns(lstrColName).Hidden = True
                    End If
                Next

                For Each lstrColName As String In mstDataSourceParentGroupDateCol
                    If rootband.Columns.Exists(lstrColName) Then
                        rootband.Columns(lstrColName).Hidden = True
                    End If
                Next
            End If

            For Each lobjListingInformation As ListingInformation In mstListingInformation
                'If rootband.Columns.Exists(mstrSOFColPrefix + mstrCurrentListingColPrefix + lobjListingInformation.ListingName) Then
                '    rootband.Columns(mstrSOFColPrefix + mstrCurrentListingColPrefix + lobjListingInformation.ListingName).Hidden = True
                'End If
                'If rootband.Columns.Exists(mstrCurrentListingColPrefix + lobjListingInformation.ListingName + mstrFormulaColSuffix) Then
                '    rootband.Columns(mstrCurrentListingColPrefix + lobjListingInformation.ListingName + mstrFormulaColSuffix).Hidden = True
                'End If
                If rootband.Columns.Exists(lobjListingInformation.ListingName + mstrSameDateUpdateCount) Then
                    rootband.Columns(lobjListingInformation.ListingName + mstrSameDateUpdateCount).Hidden = True
                End If
                If rootband.Columns.Exists(lobjListingInformation.ListingName + mstrUpdateCount) Then
                    rootband.Columns(lobjListingInformation.ListingName + mstrUpdateCount).Hidden = True
                End If
                If rootband.Columns.Exists(lobjListingInformation.ListingName + mstrSameDateDDInfoCount) Then
                    rootband.Columns(lobjListingInformation.ListingName + mstrSameDateDDInfoCount).Hidden = True
                End If
                If rootband.Columns.Exists(lobjListingInformation.ListingName + mstrDDInfoCount) Then
                    rootband.Columns(lobjListingInformation.ListingName + mstrDDInfoCount).Hidden = True
                End If
                If rootband.Columns.Exists(lobjListingInformation.ListingName + mstrSamePositionRegisterCount) Then
                    rootband.Columns(lobjListingInformation.ListingName + mstrSamePositionRegisterCount).Hidden = True
                End If
                If rootband.Columns.Exists(lobjListingInformation.ListingName + mstrSamePositionBanklistCount) Then
                    rootband.Columns(lobjListingInformation.ListingName + mstrSamePositionBanklistCount).Hidden = True
                End If
            Next
            'To enable the sorting capabilities of FL positions columns of previous project(s) so that sorting with Desc Positions can be conducted. Dupinder
            'For Each lobjPreviousProjects As PreviousProjects In mstPreviousProjects
            '    rootband.Columns(lobjPreviousProjects.DeliveryListing).SortComparer = New NumericComparer
            'Next

            e.Layout.Override.AllowUpdate = False
            'e.Layout.Override.FilterUIType = FilterUIType.FilterRow
            e.Layout.Override.FilterUIType = FilterUIType.HeaderIcons
            ' Turn on row filtering functionality.
            e.Layout.Override.AllowRowFiltering = DefaultableBoolean.True
            e.Layout.Override.RowFilterAction = RowFilterAction.HideFilteredOutRows
            e.Layout.Override.FilterOperandStyle = FilterOperandStyle.Combo
            e.Layout.Appearance.TextVAlign = Infragistics.Win.VAlign.Middle
            e.Layout.Appearance.TextHAlign = Infragistics.Win.HAlign.Center
            rootband.Columns("Name").CellAppearance.TextHAlign = Infragistics.Win.HAlign.Left
            e.Layout.Override.SelectTypeCell = Infragistics.Win.UltraWinGrid.SelectType.ExtendedAutoDrag
            e.Layout.Override.SelectTypeCol = Infragistics.Win.UltraWinGrid.SelectType.Single
            e.Layout.Override.SelectTypeRow = SelectType.Extended
            e.Layout.Override.CellClickAction = Infragistics.Win.UltraWinGrid.CellClickAction.CellSelect
            e.Layout.Bands(0).Override.MultiCellSelectionMode = MultiCellSelectionMode.Standard
            For Each lstrColumnName As String In mstSysColumns
                If rootband.Columns.Exists(lstrColumnName) Then
                    rootband.Columns(lstrColumnName).CellDisplayStyle = CellDisplayStyle.PlainText
                End If
            Next

            'Add the appereances
            lIsMasterDBAppereance = e.Layout.Appearances.Add("IsMasterDB")
            lIsMasterDBAppereance.ForeColor = Color.DarkGreen

            lUnlinkedFundAppereance = e.Layout.Appearances.Add("UnlinkedFund")
            lUnlinkedFundAppereance.ForeColor = Color.DarkRed

            'Master DB Funds associated to Project DB Investor
            lMasterDBFundAppereance = e.Layout.Appearances.Add("MasterDBFund")
            lMasterDBFundAppereance.ForeColor = Color.DarkMagenta

            lDelAndExtnctAppereance = e.Layout.Appearances.Add("DelAndExtnct")
            lDelAndExtnctAppereance.BackColor = mclrDelAndExtnct

            lDelAndExtnctDataSourceAppereance = e.Layout.Appearances.Add("DelAndExtnctDataSource")
            lDelAndExtnctDataSourceAppereance.BackColor = mclrDelAndExtnctForDataSource

            lToolTipInfoAppereance = e.Layout.Appearances.Add("ToolTipInfo")
            lToolTipInfoAppereance.BackColor = Color.FromArgb(246, 214, 115)

            lHasAnyDoubtsAppereance = e.Layout.Appearances.Add("HasAnyDoubts")
            lHasAnyDoubtsAppereance.BackColor = Color.Red

            lColHeadBackColorAppereance = e.Layout.Appearances.Add("ColHeadBackColor")
            lColHeadBackColorAppereance.BackColor = mclrColHeadBackColor

            lMandAParentRowAppereance = e.Layout.Appearances.Add("MandAParentRow")
            lMandAParentRowAppereance.ForeColor = Color.DarkOrange

            lGridForeColorAppereance = e.Layout.Appearances.Add("GridForeColor")
            lGridForeColorAppereance.ForeColor = mclrGridForeColor
            lGridForeColorAppereance.BackColor = mclrGridFundBackColor

            lGridInvAddedAppereance = e.Layout.Appearances.Add("GridInvAddedAppearance")
            lGridInvAddedAppereance.ForeColor = mclrGridForeColor
            lGridInvAddedAppereance.BackColor = mclrGridInvBackColor
            lGridInvAddedAppereance.FontData.Bold = DefaultableBoolean.True

            lCutRowBackColorAppereance = e.Layout.Appearances.Add("CutRowBackColor")
            lCutRowBackColorAppereance.BackColor = Color.FromArgb(242, 225, 229)

            lCancelCutAppereance = e.Layout.Appearances.Add("CancelCutRowBackColor")
            lCancelCutAppereance.BackColor = mclrGridFundBackColor

            lInvestorRowColorAppereance = e.Layout.Appearances.Add("GridInvBackColor")
            lInvestorRowColorAppereance.BackColor = mclrGridInvBackColor
            lInvestorRowColorAppereance.FontData.Bold = DefaultableBoolean.True

            'Dim lInvestorRowAppereance As Infragistics.Win.Appearance = e.Layout.Appearances.Add("GridInvFontBold")
            'lInvestorRowAppereance.FontData.Bold = DefaultableBoolean.True

            lFundRowAppereance = e.Layout.Appearances.Add("FundRowBackColor")
            lFundRowAppereance.BackColor = mclrGridFundBackColor

            lVisiblePositionAppereance = e.Layout.Appearances.Add("VisiblePosition")
            lVisiblePositionAppereance.BackColor = Color.FromArgb(201, 217, 233)

            lRedBAackColorAppereance = e.Layout.Appearances.Add("RedBackColor")
            lRedBAackColorAppereance.BackColor = Color.Red

            lMostRecentLastProjectAppearance = e.Layout.Appearances.Add("MostRecentLastProject")
            lMostRecentLastProjectAppearance.BackColor = Color.FromArgb(170, 188, 200)

            e.Layout.Override.RowAppearance.BackColor = grdData.DisplayLayout.Appearances("FundRowBackColor").BackColor
            e.Layout.Override.RowAlternateAppearance.BackColor = grdData.DisplayLayout.Appearances("FundRowBackColor").BackColor
            rootband.Columns("Name").CellAppearance.BackColor = e.Layout.Appearances("FundRowBackColor").BackColor

            'Copy the data of column
            e.Layout.Override.AllowMultiCellOperations = AllowMultiCellOperation.All

            'grdData.DisplayLayout.TabNavigation = TabNavigation.NextCell
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            lIsMasterDBAppereance = Nothing
            lUnlinkedFundAppereance = Nothing
            lMasterDBFundAppereance = Nothing
            lDelAndExtnctAppereance = Nothing
            lDelAndExtnctDataSourceAppereance = Nothing
            lToolTipInfoAppereance = Nothing
            lHasAnyDoubtsAppereance = Nothing
            lColHeadBackColorAppereance = Nothing
            lMandAParentRowAppereance = Nothing
            lGridForeColorAppereance = Nothing
            lCutRowBackColorAppereance = Nothing
            lCancelCutAppereance = Nothing
            lInvestorRowColorAppereance = Nothing
            lFundRowAppereance = Nothing
            lVisiblePositionAppereance = Nothing
            lMostRecentLastProjectAppearance = Nothing
            lRedBAackColorAppereance = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' Runs on the initialization of each row
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    ''' 
    Private Sub grdData_InitializeRow(ByVal sender As Object, ByVal e As Infragistics.Win.UltraWinGrid.InitializeRowEventArgs) Handles grdData.InitializeRow
        If (Me.IsDisposed) Then Exit Sub
        'If e.Row.Index = mint32RowCount Then Exit Sub
        Dim lintColCounter As Integer
        Try
            If e.ReInitialize = False Then
                ' ''To set the UserID value if it's NULL or 0
                If CommonCLL.IsNullTo0(e.Row.GetCellValue("UserID")) <> CommonCLL.UserID Then
                    e.Row.Cells("UserID").Value = CommonCLL.UserID
                End If
                'To set the UserID value if it's NULL or 0
                If CommonCLL.IsNullTo0(e.Row.GetCellValue("RowNumber")) = 0 Then
                    e.Row.Cells("RowNumber").Value = e.Row.Index + 1
                End If

                'If e.Row.GetCellValue("FundID") = 46700 Then
                '    e.Row.Cells("RowNumber").Value = e.Row.Index + 1
                'End If

                ' ''If its an Investor row, then Bold it and set the forecolor
                If CommonCLL.IsNullTo0(e.Row.GetCellValue("LinkID")) = 0 Then
                    e.Row.CellAppearance = grdData.DisplayLayout.Appearances("GridInvBackColor")
                End If

                'Set the coloring If row is being added because of Master Search
                If mblnIsFromMasterSearch Then
                    If e.Row.GetCellValue("LinkID") = 0 Then
                        'If the Investor is a MasterDB then set the color to Green
                        If e.Row.GetCellValue("IsMasterDB") = True Then
                            'e.Row.Appearance.ForeColor = Color.DarkGreen
                            e.Row.Appearance.ForeColor = grdData.DisplayLayout.Appearances("IsMasterDB").ForeColor   '.Appearances.Add("IsMasterDB") 'Color.DarkGreen
                        End If
                    Else
                        'If the fund is an unlinked fund then set the color to Red
                        If e.Row.GetCellValue("LinkID") = -1 Then
                            'e.Row.Appearance.ForeColor = Color.DarkRed
                            e.Row.Appearance.ForeColor = grdData.DisplayLayout.Appearances("UnlinkedFund").ForeColor ' Color.DarkRed
                        Else
                            'Master DB Funds associated to Project DB Investor(s) should be in a Magenta.
                            If e.Row.GetCellValue("IsMasterDB") = True Then
                                'To run the code only once for the Investor row
                                If e.Row.GetCellValue("IsMasterDB") = True And e.Row.GetCellValue("InvestorID") <> mintLastTranversedInvestorID Then
                                    Dim ldrInvestorRow As DataRow
                                    ldrInvestorRow = CType(grdData.DataSource, DataTable).Rows.Find(New Object() {e.Row.GetCellValue("InvestorID"), 0})
                                    If ldrInvestorRow Is Nothing Then Exit Sub
                                    mintLastTranversedInvIndex = CType(grdData.DataSource, DataTable).Rows.IndexOf(ldrInvestorRow)
                                    mintLastTranversedInvestorID = e.Row.GetCellValue("InvestorID")
                                    If grdData.Rows(mintLastTranversedInvIndex).GetCellValue("IsMasterDB") = False Then
                                        'grdData.Rows(mintLastTranversedInvIndex).Appearance.ForeColor = Color.DarkMagenta
                                        grdData.Rows(mintLastTranversedInvIndex).Appearance.ForeColor = grdData.DisplayLayout.Appearances("MasterDBFund").ForeColor  'Color.DarkMagenta
                                    End If
                                End If
                            End If
                        End If
                    End If
                End If
            End If

            If menmScreenType = DataHubScreenType.FinalizeList Then
                For Each lobjListingInformation As ListingInformation In mstListingInformation
                    If e.Row.Band.Columns.Exists(lobjListingInformation.ListingName + mstrSameDateUpdateCount) Then
                        If e.Row.GetCellValue(lobjListingInformation.ListingName + mstrSameDateUpdateCount) IsNot DBNull.Value Then
                            e.Row.Cells(mstrUpdatesColPrefix + lobjListingInformation.ListingName).ToolTipText = MessageManager.GetMessage(DBResult.FL_UPD_SAME_SOURCEDATE.ToString)
                        End If
                    End If

                    If e.Row.Band.Columns.Exists(lobjListingInformation.ListingName + mstrUpdateCount) Then
                        If e.Row.GetCellValue(lobjListingInformation.ListingName + mstrUpdateCount) IsNot DBNull.Value Then
                            e.Row.Cells(mstrUpdatesColPrefix + lobjListingInformation.ListingName).Appearance.FontData.Underline = Infragistics.Win.DefaultableBoolean.True
                        End If
                    End If

                    If e.Row.Band.Columns.Exists(lobjListingInformation.ListingName + mstrSameDateDDInfoCount) Then
                        If e.Row.GetCellValue(lobjListingInformation.ListingName + mstrSameDateDDInfoCount) IsNot DBNull.Value Then
                            e.Row.Cells(mstrDDInfoColPrefix + lobjListingInformation.ListingName).ToolTipText = MessageManager.GetMessage(DBResult.FL_DDI_SAME_SOURCEDATE.ToString)
                        End If
                    End If

                    If e.Row.Band.Columns.Exists(lobjListingInformation.ListingName + mstrDDInfoCount) Then
                        If e.Row.GetCellValue(lobjListingInformation.ListingName + mstrDDInfoCount) IsNot DBNull.Value Then
                            e.Row.Cells(mstrDDInfoColPrefix + lobjListingInformation.ListingName).Appearance.FontData.Underline = Infragistics.Win.DefaultableBoolean.True
                        End If
                    End If

                    If e.Row.Band.Columns.Exists(lobjListingInformation.ListingName + mstrSamePositionRegisterCount) Then
                        If e.Row.GetCellValue(lobjListingInformation.ListingName + mstrSamePositionRegisterCount) IsNot DBNull.Value Then
                            e.Row.Cells(mstrRegisterColPrefix + lobjListingInformation.ListingName).Appearance.FontData.Underline = Infragistics.Win.DefaultableBoolean.True
                        End If
                    End If

                    If e.Row.Band.Columns.Exists(lobjListingInformation.ListingName + mstrSamePositionBanklistCount) Then
                        If e.Row.GetCellValue(lobjListingInformation.ListingName + mstrSamePositionBanklistCount) IsNot DBNull.Value Then
                            e.Row.Cells(mstrBanklistColPrefix + lobjListingInformation.ListingName).Appearance.FontData.Underline = Infragistics.Win.DefaultableBoolean.True
                        End If
                    End If
                Next
            End If
            '' ''To set the Investor/Fund in different color if status is Delete/Extinct
            If Convert.ToString(e.Row.GetCellValue("InvStatusCode")) = Crystal.CLL.EntityStatus.DELTE.ToString OrElse _
                Convert.ToString(e.Row.GetCellValue("InvStatusCode")) = Crystal.CLL.EntityStatus.EXTNT.ToString Then
                If e.Row.GetCellValue("InvStatusCode") = Crystal.CLL.EntityStatus.DELTE.ToString Then
                    e.Row.Cells("Name").Appearance.BackColor = grdData.DisplayLayout.Appearances("DelAndExtnct").BackColor 'mclrDelAndExtnct
                End If

                'If the row is Delete/Extinct, then mark the data source color with a different one
                lintColCounter = mintParentIndex + 1
                While lintColCounter < mintTypeColIndex
                    'grdData.DisplayLayout.Override.ActiveCellAppearance.BackColor = grdData.DisplayLayout.Appearances("DelAndExtnctDataSource").BackColor 'DelAndExtnctDataSource mclrDelAndExtnctForDataSource
                    e.Row.Cells(lintColCounter).Appearance.BackColor = grdData.DisplayLayout.Appearances("DelAndExtnctDataSource").BackColor
                    lintColCounter += 1
                End While
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        End Try
    End Sub

    ''' <summary>
    ''' To load the Notes on change of each row
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub grdData_AfterRowActivate(ByVal sender As Object, ByVal e As System.EventArgs) Handles grdData.AfterRowActivate
        If mblnCheckNewRow Then Exit Sub
        If spcDataHub.Panel2Collapsed = False Then
            LoadNotes()
        End If
    End Sub

    ''' <summary>
    ''' To disallow the change in column's index if they are prohibted
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub grdData_BeforeColPosChanged(ByVal sender As Object, ByVal e As Infragistics.Win.UltraWinGrid.BeforeColPosChangedEventArgs) Handles grdData.BeforeColPosChanged
        If PosChanged.Moved = e.PosChanged OrElse PosChanged.Swapped = e.PosChanged Then
            Dim lobjCurrentDataSources As CurrentDataSources = Nothing
            Dim lstrSourceName As String = ""
            Dim lstrMovingNextColName As String = ""
            Dim lintVisiblePosition As Integer = 0
            Try
                For Each lColHeader As UltraWinGrid.ColumnHeader In e.ColumnHeaders
                    'Some pre-defined columns are not allowed to be moved.
                    If lColHeader.Caption = "Notes" OrElse lColHeader.Caption = "Origin" OrElse lColHeader.Caption = "InvestorName" OrElse lColHeader.Caption = "Name" OrElse _
                        lColHeader.Caption = "ID" OrElse lColHeader.Caption = "Status" OrElse mstPublicSourcesCols.Contains(lColHeader.Caption) OrElse _
                        mstPublicFilingDateCols.Contains(lColHeader.Caption) Then
                        e.Cancel = True
                    End If
                    'Get the name of the column next to currently selected columns' new position
                    For Each lCol As UltraGridColumn In grdData.Rows.Band.Columns
                        If lCol.Hidden Then Continue For
                        If lColHeader.VisiblePosition < grdData.Rows.Band.Columns(lColHeader.Caption).Header.VisiblePosition Then
                            If lColHeader.VisiblePosition <= lCol.Header.VisiblePosition Then
                                If lintVisiblePosition = 0 Then
                                    lintVisiblePosition = lCol.Header.VisiblePosition
                                    lstrMovingNextColName = lCol.Header.Caption
                                End If
                                If lintVisiblePosition >= lCol.Header.VisiblePosition Then
                                    lintVisiblePosition = lCol.Header.VisiblePosition
                                    lstrMovingNextColName = lCol.Header.Caption
                                End If
                            End If
                        Else
                            If lColHeader.VisiblePosition < lCol.Header.VisiblePosition AndAlso _
                                (lColHeader.Caption + mstrSourceDateColSuffix <> lCol.Header.Caption OrElse lColHeader.Caption + mstrSourceColSuffix <> lCol.Header.Caption OrElse _
                                 lColHeader.Caption + mstrFilingDateColSuffix <> lCol.Header.Caption) _
                                Then
                                If lintVisiblePosition = 0 Then
                                    lintVisiblePosition = lCol.Header.VisiblePosition
                                    lstrMovingNextColName = lCol.Header.Caption
                                End If
                                If lintVisiblePosition > lCol.Header.VisiblePosition Then
                                    lintVisiblePosition = lCol.Header.VisiblePosition
                                    lstrMovingNextColName = lCol.Header.Caption
                                End If
                            End If
                        End If
                    Next
                    If lstrMovingNextColName = "" Then
                        e.Cancel = True
                    Else
                        ''Commented as Public Filing Date and Source cannot be moved
                        If mstResearchSourceCols.Contains(lstrMovingNextColName) Then
                            lstrSourceName = lstrMovingNextColName.Substring(0, lstrMovingNextColName.Length - mstrSourceColSuffix.Length)
                        End If
                        'If the column next to currently selected columns' new position is a date then disallow it, because a column can't be put in between a column and it's date column.
                        If (mstAllDataSourceDateCols.Contains(lstrMovingNextColName) AndAlso lstrMovingNextColName.Substring(0, lstrMovingNextColName.Length - mstrSourceDateColSuffix.Length) <> lColHeader.Caption) _
                            OrElse (mstPublicFilingDateCols.Contains(lstrMovingNextColName) AndAlso lstrMovingNextColName.Substring(0, lstrMovingNextColName.Length - mstrFilingDateColSuffix.Length) <> lColHeader.Caption) _
                            OrElse (mstPublicSourcesCols.Contains(lstrMovingNextColName) AndAlso lstrMovingNextColName.Substring(0, lstrMovingNextColName.Length - mstrSourceColSuffix.Length) <> lColHeader.Caption) _
                            OrElse (mstResearchSourceCols.Contains(lstrMovingNextColName) AndAlso lstrSourceName <> lColHeader.Caption AndAlso lstrSourceName + mstrSourceDateColSuffix <> lColHeader.Caption) _
                            OrElse (mstDataSourceParentGroupDateCol.Contains(lstrMovingNextColName) AndAlso lstrMovingNextColName.Substring(0, lstrMovingNextColName.Length - mstrSourceDateColSuffix.Length) <> lColHeader.Caption) _
                            OrElse lstrMovingNextColName.StartsWith(mstrFLCurrentListingPrefix) _
                            Then
                            e.Cancel = True
                        End If
                    End If
                Next
            Catch ex As Exception
                Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
            Finally
                lobjCurrentDataSources = Nothing
            End Try
        End If
    End Sub

    ''' <summary>
    ''' To move an associate child column along with the parent column and vice versa
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub grdData_AfterColPosChanged(ByVal sender As Object, ByVal e As Infragistics.Win.UltraWinGrid.AfterColPosChangedEventArgs) Handles grdData.AfterColPosChanged
        If PosChanged.Moved = e.PosChanged OrElse PosChanged.Swapped = e.PosChanged Then
            Dim lobjCurrentDataSources As CurrentDataSources = Nothing
            Dim lintCurrentColVisiblePosition As Integer
            Dim lintSourceNameIndex As Integer
            Dim lintSourceDateIndex As Integer
            Dim lintResearchSourceIndex As Integer = -1
            Dim lstrColHeader As String = ""
            Dim lblnIsFromSourceName As Boolean = True
            Dim lenmFixedStateColumnType As FixedStateColumnType
            Dim rootband As UltraGridBand = grdData.Rows.Band
            Dim lintParentColIndex As Integer
            Dim lintChildColIndex As Integer
            Dim lobjListingInformation As ListingInformation = Nothing
            Dim lstrListingName As String
            Try
                For Each lColHeader As UltraWinGrid.ColumnHeader In e.ColumnHeaders
                    lenmFixedStateColumnType = FixedStateColumnType.None
                    lstrColHeader = lColHeader.Caption
                    If lstrColHeader.StartsWith(mstrFLCurrentListingPrefix) OrElse lstrColHeader.StartsWith(mstrFLSuggestedFinalListingPrefix) AndAlso menmScreenType = DataHubScreenType.FinalizeList Then
                        If lstrColHeader.StartsWith(mstrFLCurrentListingPrefix) Then
                            lstrListingName = lstrColHeader.TrimStart(mstrFLCurrentListingPrefix.ToArray)
                            lobjListingInformation = mstListingInformation.Find(Function(p) p.ListingName = lstrListingName)
                            lintParentColIndex = rootband.Columns(mstrFLSuggestedFinalListingPrefix + lobjListingInformation.ListingName).Header.VisiblePosition
                            lintChildColIndex = rootband.Columns(lobjListingInformation.CurrentListingName).Header.VisiblePosition

                            If lintParentColIndex > lintChildColIndex Then
                                While True
                                    lintParentColIndex = rootband.Columns(mstrFLSuggestedFinalListingPrefix + lobjListingInformation.ListingName).Header.VisiblePosition
                                    lintChildColIndex = rootband.Columns(lobjListingInformation.CurrentListingName).Header.VisiblePosition
                                    If lintChildColIndex = lintParentColIndex + 1 Then
                                        Exit While
                                    End If
                                    rootband.Columns(mstrFLSuggestedFinalListingPrefix + lobjListingInformation.ListingName).Header.VisiblePosition = lintParentColIndex - 1
                                End While
                            End If
                            If lintParentColIndex < lintChildColIndex Then
                                While True
                                    lintParentColIndex = rootband.Columns(mstrFLSuggestedFinalListingPrefix + lobjListingInformation.ListingName).Header.VisiblePosition
                                    lintChildColIndex = rootband.Columns(lobjListingInformation.CurrentListingName).Header.VisiblePosition
                                    If lintChildColIndex = lintParentColIndex + 1 Then
                                        Exit While
                                    End If
                                    rootband.Columns(mstrFLSuggestedFinalListingPrefix + lobjListingInformation.ListingName).Header.VisiblePosition = lintParentColIndex + 1
                                End While
                            End If
                        Else
                            lstrListingName = lstrColHeader.TrimStart(mstrFLSuggestedFinalListingPrefix.ToArray)
                            lobjListingInformation = mstListingInformation.Find(Function(p) p.ListingName = lstrListingName)
                            lintParentColIndex = rootband.Columns(mstrFLSuggestedFinalListingPrefix + lobjListingInformation.ListingName).Header.VisiblePosition
                            lintChildColIndex = rootband.Columns(lobjListingInformation.CurrentListingName).Header.VisiblePosition

                            If lintParentColIndex > lintChildColIndex Then
                                While True
                                    lintParentColIndex = rootband.Columns(mstrFLSuggestedFinalListingPrefix + lobjListingInformation.ListingName).Header.VisiblePosition
                                    lintChildColIndex = rootband.Columns(lobjListingInformation.CurrentListingName).Header.VisiblePosition
                                    If lintChildColIndex = lintParentColIndex + 1 Then
                                        Exit While
                                    End If
                                    rootband.Columns(lobjListingInformation.CurrentListingName).Header.VisiblePosition = lintChildColIndex + 1
                                End While
                            End If
                            If lintParentColIndex < lintChildColIndex Then
                                While True
                                    lintParentColIndex = rootband.Columns(mstrFLSuggestedFinalListingPrefix + lobjListingInformation.ListingName).Header.VisiblePosition
                                    lintChildColIndex = rootband.Columns(lobjListingInformation.CurrentListingName).Header.VisiblePosition
                                    If lintChildColIndex = lintParentColIndex + 1 Then
                                        Exit While
                                    End If
                                    rootband.Columns(lobjListingInformation.CurrentListingName).Header.VisiblePosition = lintChildColIndex - 1
                                End While
                            End If
                        End If
                    ElseIf (lstrColHeader.StartsWith(mstrUpdatesColPrefix) OrElse lstrColHeader.StartsWith(mstrDDInfoColPrefix) OrElse _
                            lstrColHeader.StartsWith(mstrRegisterColPrefix) OrElse lstrColHeader.StartsWith(mstrBanklistColPrefix)) _
                        AndAlso menmScreenType = DataHubScreenType.FinalizeList AndAlso mstAllDataSourceNameCols.Contains(lstrColHeader) = False AndAlso _
                        mstAllDataSourceNameCols.Contains(lstrColHeader) = False Then
                        If lstrColHeader.Contains(mstrSourceDateColSuffix) Then
                            lintParentColIndex = rootband.Columns(lstrColHeader.TrimEnd(mstrSourceDateColSuffix.Trim.ToArray).Trim).Header.VisiblePosition
                            lintChildColIndex = rootband.Columns(lstrColHeader).Header.VisiblePosition

                            If lintParentColIndex > lintChildColIndex Then
                                While True
                                    lintParentColIndex = rootband.Columns(lstrColHeader.TrimEnd(mstrSourceDateColSuffix.Trim.ToArray).Trim).Header.VisiblePosition
                                    lintChildColIndex = rootband.Columns(lstrColHeader).Header.VisiblePosition
                                    If lintChildColIndex = lintParentColIndex + 1 Then
                                        Exit While
                                    End If
                                    rootband.Columns(lstrColHeader.TrimEnd(mstrSourceDateColSuffix.Trim.ToArray).Trim).Header.VisiblePosition = lintParentColIndex - 1
                                End While
                            End If
                            If lintParentColIndex < lintChildColIndex Then
                                While True
                                    lintParentColIndex = rootband.Columns(lstrColHeader.TrimEnd(mstrSourceDateColSuffix.Trim.ToArray).Trim).Header.VisiblePosition
                                    lintChildColIndex = rootband.Columns(lstrColHeader).Header.VisiblePosition
                                    If lintChildColIndex = lintParentColIndex + 1 Then
                                        Exit While
                                    End If
                                    rootband.Columns(lstrColHeader.TrimEnd(mstrSourceDateColSuffix.Trim.ToArray).Trim).Header.VisiblePosition = lintParentColIndex + 1
                                End While
                            End If
                        Else
                            If rootband.Columns.Exists(lstrColHeader + mstrSourceDateColSuffix) Then
                                lintParentColIndex = rootband.Columns(lstrColHeader).Header.VisiblePosition
                                lintChildColIndex = rootband.Columns(lstrColHeader + mstrSourceDateColSuffix).Header.VisiblePosition

                                If lintParentColIndex > lintChildColIndex Then
                                    While True
                                        lintParentColIndex = rootband.Columns(lstrColHeader).Header.VisiblePosition
                                        lintChildColIndex = rootband.Columns(lstrColHeader + mstrSourceDateColSuffix).Header.VisiblePosition
                                        If lintChildColIndex = lintParentColIndex + 1 Then
                                            Exit While
                                        End If
                                        rootband.Columns(lstrColHeader + mstrSourceDateColSuffix).Header.VisiblePosition = lintChildColIndex + 1
                                    End While
                                End If
                                If lintParentColIndex < lintChildColIndex Then
                                    While True
                                        lintParentColIndex = rootband.Columns(lstrColHeader).Header.VisiblePosition
                                        lintChildColIndex = rootband.Columns(lstrColHeader + mstrSourceDateColSuffix).Header.VisiblePosition
                                        If lintChildColIndex = lintParentColIndex + 1 Then
                                            Exit While
                                        End If
                                        rootband.Columns(lstrColHeader + mstrSourceDateColSuffix).Header.VisiblePosition = lintChildColIndex - 1
                                    End While
                                End If
                            End If
                        End If
                    Else
                        lobjCurrentDataSources = mstCurrentDataSources.Find(Function(p) p.SourceName = lstrColHeader)
                        'If the selected column is a date column
                        If lobjCurrentDataSources Is Nothing Then
                            lobjCurrentDataSources = mstCurrentDataSources.Find(Function(p) p.SourceDate = lstrColHeader)
                            If lobjCurrentDataSources Is Nothing Then
                                lobjCurrentDataSources = mstCurrentDataSources.Find(Function(p) p.ResearchSourceCol = lstrColHeader)
                                If lobjCurrentDataSources IsNot Nothing Then
                                    'lenmFixedStateColumnType = FixedStateColumnType.ResearchSource
                                End If
                            Else
                                'lenmFixedStateColumnType = FixedStateColumnType.SourceDate
                            End If
                            If lobjCurrentDataSources Is Nothing Then Exit Sub
                            lblnIsFromSourceName = False
                            lenmFixedStateColumnType = GetFixedStateType(lstrColHeader)
                            If lenmFixedStateColumnType <> FixedStateColumnType.None Then
                                SetColumnFixedState(lobjCurrentDataSources, lenmFixedStateColumnType)
                            End If
                            'If lobjCurrentDataSources.SourceDate.Equals("") = False Then
                            '    SetColumnFixedState(lobjCurrentDataSources, lenmFixedStateColumnType)
                            'End If
                            If marrDateSuppertedSourceTypes.Contains(lobjCurrentDataSources.ESourceCode) AndAlso rootband.Columns.Exists(lobjCurrentDataSources.SourceDate) Then
                                'If ldrDataSource("SourceTypeCode") = SourceTypeCode.UPD.ToString OrElse ldrDataSource("SourceTypeCode") = SourceTypeCode.DDQ.ToString Then
                                lintCurrentColVisiblePosition = rootband.Columns(lobjCurrentDataSources.SourceDate).Header.VisiblePosition
                                lintSourceNameIndex = rootband.Columns(lobjCurrentDataSources.SourceName).Header.VisiblePosition
                                lintSourceDateIndex = rootband.Columns(lobjCurrentDataSources.SourceDate).Header.VisiblePosition
                                If rootband.Columns.Exists(lobjCurrentDataSources.ResearchSourceCol) Then
                                    lintResearchSourceIndex = rootband.Columns(lobjCurrentDataSources.ResearchSourceCol).Header.VisiblePosition
                                End If

                                If lintResearchSourceIndex > -1 AndAlso lstrColHeader.Equals(lobjCurrentDataSources.ResearchSourceCol) Then
                                    If lintSourceDateIndex <> lintSourceNameIndex + 1 OrElse lintResearchSourceIndex <> lintSourceNameIndex + 2 Then
                                        If lintSourceDateIndex > lintResearchSourceIndex Then
                                            While True
                                                lintSourceDateIndex = rootband.Columns(lobjCurrentDataSources.SourceDate).Header.VisiblePosition
                                                lintResearchSourceIndex = rootband.Columns(lobjCurrentDataSources.ResearchSourceCol).Header.VisiblePosition
                                                If lintResearchSourceIndex = lintSourceDateIndex + 1 Then
                                                    Exit While
                                                End If
                                                rootband.Columns(lobjCurrentDataSources.SourceDate).Header.VisiblePosition = lintSourceDateIndex - 1
                                            End While
                                        End If

                                        If lintSourceDateIndex < lintResearchSourceIndex Then
                                            While True
                                                lintSourceDateIndex = rootband.Columns(lobjCurrentDataSources.SourceDate).Header.VisiblePosition
                                                lintResearchSourceIndex = rootband.Columns(lobjCurrentDataSources.ResearchSourceCol).Header.VisiblePosition
                                                If lintResearchSourceIndex = lintSourceDateIndex + 1 Then
                                                    Exit While
                                                End If
                                                rootband.Columns(lobjCurrentDataSources.SourceDate).Header.VisiblePosition = lintSourceDateIndex + 1
                                            End While
                                        End If

                                        If lintSourceNameIndex > lintSourceDateIndex Then
                                            While True
                                                lintSourceDateIndex = rootband.Columns(lobjCurrentDataSources.SourceDate).Header.VisiblePosition
                                                lintSourceNameIndex = rootband.Columns(lobjCurrentDataSources.SourceName).Header.VisiblePosition
                                                If lintSourceDateIndex = lintSourceNameIndex + 1 Then
                                                    Exit While
                                                End If
                                                rootband.Columns(lobjCurrentDataSources.SourceName).Header.VisiblePosition = lintSourceNameIndex - 1
                                            End While
                                        End If
                                        If lintSourceNameIndex < lintSourceDateIndex Then
                                            While True
                                                lintSourceDateIndex = rootband.Columns(lobjCurrentDataSources.SourceDate).Header.VisiblePosition
                                                lintSourceNameIndex = rootband.Columns(lobjCurrentDataSources.SourceName).Header.VisiblePosition
                                                If lintSourceDateIndex = lintSourceNameIndex + 1 Then
                                                    Exit While
                                                End If
                                                rootband.Columns(lobjCurrentDataSources.SourceName).Header.VisiblePosition = lintSourceNameIndex + 1
                                            End While
                                        End If
                                    End If
                                Else
                                    If lintSourceNameIndex > lintSourceDateIndex Then
                                        While True
                                            lintSourceDateIndex = rootband.Columns(lobjCurrentDataSources.SourceDate).Header.VisiblePosition
                                            lintSourceNameIndex = rootband.Columns(lobjCurrentDataSources.SourceName).Header.VisiblePosition
                                            If lintSourceDateIndex = lintSourceNameIndex + 1 Then
                                                Exit While
                                            End If
                                            rootband.Columns(lobjCurrentDataSources.SourceName).Header.VisiblePosition = lintSourceNameIndex - 1
                                        End While
                                        If lobjCurrentDataSources.SourceTypeCode = SourceTypeCode.RSH.ToString Then
                                            rootband.Columns(lobjCurrentDataSources.ResearchSourceCol).Header.VisiblePosition = lintSourceNameIndex + 2
                                        End If
                                    End If
                                    If lintSourceNameIndex < lintSourceDateIndex Then
                                        While True
                                            lintSourceDateIndex = rootband.Columns(lobjCurrentDataSources.SourceDate).Header.VisiblePosition
                                            lintSourceNameIndex = rootband.Columns(lobjCurrentDataSources.SourceName).Header.VisiblePosition
                                            If lintSourceDateIndex = lintSourceNameIndex + 1 Then
                                                Exit While
                                            End If
                                            rootband.Columns(lobjCurrentDataSources.SourceName).Header.VisiblePosition = lintSourceNameIndex + 1
                                        End While
                                        If lobjCurrentDataSources.SourceTypeCode = SourceTypeCode.RSH.ToString AndAlso rootband.Columns(lobjCurrentDataSources.ResearchSourceCol).Header.VisiblePosition <> lintSourceNameIndex + 2 Then
                                            rootband.Columns(lobjCurrentDataSources.ResearchSourceCol).Header.VisiblePosition = lintSourceNameIndex + 1
                                        End If
                                    End If
                                End If
                            End If
                            'ElseIf the selected column is a Position column
                        Else
                            'If ldrDataSource("SourceTypeCode") = SourceTypeCode.UPD.ToString OrElse ldrDataSource("SourceTypeCode") = SourceTypeCode.DDQ.ToString Then
                            lenmFixedStateColumnType = GetFixedStateType(lstrColHeader)
                            If lenmFixedStateColumnType <> FixedStateColumnType.None Then
                                SetColumnFixedState(lobjCurrentDataSources, lenmFixedStateColumnType)
                            End If
                            lintSourceNameIndex = rootband.Columns(lobjCurrentDataSources.SourceName).Header.VisiblePosition
                            If marrDateSuppertedSourceTypes.Contains(lobjCurrentDataSources.ESourceCode) AndAlso rootband.Columns.Exists(lobjCurrentDataSources.SourceDate) Then
                                lintSourceDateIndex = rootband.Columns(lobjCurrentDataSources.SourceDate).Header.VisiblePosition
                                If lintSourceNameIndex > lintSourceDateIndex Then
                                    While True
                                        lintSourceDateIndex = rootband.Columns(lobjCurrentDataSources.SourceDate).Header.VisiblePosition
                                        lintSourceNameIndex = rootband.Columns(lobjCurrentDataSources.SourceName).Header.VisiblePosition
                                        If lintSourceDateIndex = lintSourceNameIndex + 1 Then
                                            Exit While
                                        End If
                                        rootband.Columns(lobjCurrentDataSources.SourceDate).Header.VisiblePosition = lintSourceDateIndex + 1
                                    End While
                                    If lobjCurrentDataSources.SourceTypeCode = SourceTypeCode.RSH.ToString Then
                                        rootband.Columns(lobjCurrentDataSources.ResearchSourceCol).Header.VisiblePosition = lintSourceNameIndex + 1
                                    End If
                                End If

                                If lintSourceNameIndex < lintSourceDateIndex Then
                                    While True
                                        lintSourceDateIndex = rootband.Columns(lobjCurrentDataSources.SourceDate).Header.VisiblePosition
                                        lintSourceNameIndex = rootband.Columns(lobjCurrentDataSources.SourceName).Header.VisiblePosition
                                        If lintSourceDateIndex = lintSourceNameIndex + 1 Then
                                            Exit While
                                        End If
                                        rootband.Columns(lobjCurrentDataSources.SourceDate).Header.VisiblePosition = lintSourceDateIndex - 1
                                    End While
                                End If
                                If lobjCurrentDataSources.SourceTypeCode = SourceTypeCode.RSH.ToString AndAlso rootband.Columns(lobjCurrentDataSources.ResearchSourceCol).Header.VisiblePosition <> lintSourceNameIndex + 2 Then
                                    rootband.Columns(lobjCurrentDataSources.ResearchSourceCol).Header.VisiblePosition = lintSourceNameIndex + 2
                                End If
                            End If
                            If lobjCurrentDataSources.SourceTypeCode = SourceTypeCode.PBC.ToString Then
                                If rootband.Columns(lobjCurrentDataSources.PublicFilingDateCol).Header.VisiblePosition > lintSourceNameIndex Then
                                    rootband.Columns(lobjCurrentDataSources.PublicFilingDateCol).Header.VisiblePosition = lintSourceNameIndex + 1
                                    rootband.Columns(lobjCurrentDataSources.PublicSourceCol).Header.VisiblePosition = lintSourceNameIndex + 2
                                Else
                                    rootband.Columns(lobjCurrentDataSources.PublicFilingDateCol).Header.VisiblePosition = lintSourceNameIndex
                                    rootband.Columns(lobjCurrentDataSources.PublicSourceCol).Header.VisiblePosition = lintSourceNameIndex
                                End If
                            End If
                        End If
                        lenmFixedStateColumnType = GetFixedStateType(lstrColHeader)
                        If lenmFixedStateColumnType <> FixedStateColumnType.None Then
                            SetColumnFixedState(lobjCurrentDataSources, lenmFixedStateColumnType)
                        End If

                        If mstPublicFilingDateCols.Contains(lstrColHeader) Then
                            lenmFixedStateColumnType = FixedStateColumnType.PublicFilingDate
                        ElseIf mstPublicSourcesCols.Contains(lstrColHeader) Then
                            lenmFixedStateColumnType = FixedStateColumnType.PublicSource
                        ElseIf mstResearchSourceCols.Contains(lstrColHeader) AndAlso rootband.Columns.Exists(lstrColHeader) Then
                            lenmFixedStateColumnType = FixedStateColumnType.ResearchSource
                        ElseIf mstAllDataSourceDateCols.Contains(lstrColHeader) AndAlso rootband.Columns.Exists(lstrColHeader) Then
                            lenmFixedStateColumnType = FixedStateColumnType.SourceDate
                        ElseIf mstAllDataSourceNameCols.Contains(lstrColHeader) AndAlso rootband.Columns.Exists(lstrColHeader) Then
                            lenmFixedStateColumnType = FixedStateColumnType.SourceName
                        End If
                        If lenmFixedStateColumnType <> FixedStateColumnType.None Then
                            SetColumnFixedState(lobjCurrentDataSources, lenmFixedStateColumnType)
                        End If
                    End If
                Next
            Catch ex As Exception
                Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
            Finally
                lobjCurrentDataSources = Nothing
                lenmFixedStateColumnType = Nothing
            End Try
        End If
    End Sub

    ''' <summary>
    ''' To disallow getting into Edit mode if the current fund row OR Investor row is DELETE or EXTINCT
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub grdData_BeforeEnterEditMode(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles grdData.BeforeEnterEditMode
        'If some positions are changed after a Cut operation, then Cancel out the cut operation
        Dim lurInvestorRow As UltraGridRow
        Dim lblnShouldCheckInvestorRow As Boolean = True
        Dim lstrPositionColName As String = ""
        Dim lblnIsSumOfFunds As Boolean
        Dim lintInvestorRowIndex As Integer
        Try
            If mblnIsCutOperationInProgress Then
                CancelOutCutOperation()
            End If
            If (mstEditableDataSourceNameCols.Contains(grdData.ActiveCell.Column.Header.Caption) = False AndAlso _
                marrPreviousProjects.Contains(grdData.ActiveCell.Column.Header.Caption) = False AndAlso _
                mstAllDataSourceDateCols.Contains(grdData.ActiveCell.Column.Header.Caption) = False AndAlso _
                grdData.ActiveCell.Column.Header.Caption.StartsWith(mstrFLCurrentListingPrefix) = False) OrElse _
                mstResearchDateCols.Contains(grdData.ActiveCell.Column.Header.Caption) Then
                e.Cancel = True
                Exit Sub
            End If
            If grdData.ActiveCell Is Nothing Then Exit Sub
            lurInvestorRow = grdData.ActiveCell.Row
            If grdData.ActiveRow.IsFilterRow Then Exit Sub
            If mstEditableDataSourceNameCols.Contains(grdData.ActiveCell.Column.Header.Caption) Then
                lstrPositionColName = grdData.ActiveCell.Column.Header.Caption
            ElseIf mstAllDataSourceDateCols.Contains(grdData.ActiveCell.Column.Header.Caption) Then
                'mstCurrentDataSources.Find(Function(p) p.SourceName = grdData.ActiveCell.Column.Header.Caption)
                lstrPositionColName = mstCurrentDataSources.Find(Function(p) p.SourceDate = grdData.ActiveCell.Column.Header.Caption).SourceName
            ElseIf marrPreviousProjects.Contains(grdData.ActiveCell.Column.Header.Caption) Then
                'mstCurrentDataSources.Find(Function(p) p.SourceName = grdData.ActiveCell.Column.Header.Caption)
                lstrPositionColName = mstPreviousProjects.Find(Function(p) p.DeliveryListing = grdData.ActiveCell.Column.Header.Caption).DeliveryListing
            ElseIf grdData.ActiveCell.Column.Header.Caption.StartsWith(mstrCurrentListingColPrefix) Then
                'mstCurrentDataSources.Find(Function(p) p.SourceName = grdData.ActiveCell.Column.Header.Caption)
                lstrPositionColName = mstListingInformation.Find(Function(p) p.CurrentListingName = grdData.ActiveCell.Column.Header.Caption).CurrentListingName
            End If
            'Check If the active row itself is delete or extinct
            If lurInvestorRow.GetCellValue("InvStatusCode") = Crystal.CLL.EntityStatus.DELTE.ToString OrElse lurInvestorRow.GetCellValue("InvStatusCode") = Crystal.CLL.EntityStatus.EXTNT.ToString Then
                If grdData.ActiveRow.GetCellValue(lstrPositionColName).ToString = "" OrElse grdData.ActiveRow.GetCellValue(lstrPositionColName).ToString = "0" Then
                    lblnShouldCheckInvestorRow = False
                    e.Cancel = True
                    Exit Sub
                End If
            End If

            'Check If the active row itself is not delete or extinct But the Investor row is extinct/delete
            If lblnShouldCheckInvestorRow AndAlso lurInvestorRow.GetCellValue("LinkID") > 0 Then
                lurInvestorRow = grdData.Rows(FindInvestorIndex(grdData.ActiveCell.Row.Index))
                If lurInvestorRow.GetCellValue("InvStatusCode") = Crystal.CLL.EntityStatus.DELTE.ToString OrElse lurInvestorRow.GetCellValue("InvStatusCode") = Crystal.CLL.EntityStatus.EXTNT.ToString Then
                    If grdData.ActiveRow.GetCellValue(lstrPositionColName).ToString = "" OrElse grdData.ActiveRow.GetCellValue(lstrPositionColName).ToString = "0" Then
                        e.Cancel = True
                        Exit Sub
                    End If
                End If
            End If

            'Check If the current column is a data source
            If mstCurrentDataSources.Find(Function(p) p.SourceName = grdData.ActiveCell.Column.Header.Caption) IsNot Nothing OrElse _
                mstPreviousProjects.Find(Function(p) p.DeliveryListing = grdData.ActiveCell.Column.Header.Caption) IsNot Nothing OrElse _
                grdData.ActiveCell.Column.Header.Caption.StartsWith(mstrCurrentListingColPrefix) Then
                If grdData.ActiveCell.Row.GetCellValue("IsManaged") = True Then
                    'Check if the currently selected column supports SOF column
                    lblnIsSumOfFunds = True
                    lintInvestorRowIndex = FindInvestorIndex(grdData.ActiveCell.Row.Index)
                    lblnIsSumOfFunds = CheckSumOfFunds(grdData.Rows(lintInvestorRowIndex).GetCellValue("InvestorID"), grdData.ActiveCell.Column.Header.Caption, True, True)
                    'lblnIsSumOfFunds = CheckSumOfFunds(lintInvestorRowIndex, grdData.ActiveCell.Column.Header.Caption)
                    If lblnIsSumOfFunds = False Then
                        e.Cancel = True
                    End If
                End If
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            lurInvestorRow = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' Update the other associated cell's values before exiting the edit mode
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub grdData_BeforeExitEditMode(ByVal sender As Object, ByVal e As Infragistics.Win.UltraWinGrid.BeforeExitEditModeEventArgs) Handles grdData.BeforeExitEditMode
        Dim lobjCurrentCol As CurrentDataSources = Nothing
        Dim lblnIsFromDataSource As Boolean = True
        Dim lstrActiveCellValue As String
        Dim lstrFormulaColName As String
        Dim lstrCalculatedValue As String
        Dim lblnCanExit As Boolean = False
        Try
            If grdData.ActiveCell Is Nothing Then Exit Sub
            'If grdData.ActiveCell.Text.ToString
            If mstEditableDataSourceNameCols.Contains(grdData.ActiveCell.Column.Header.Caption) OrElse _
                marrPreviousProjects.Contains(grdData.ActiveCell.Column.Header.Caption) OrElse _
                grdData.ActiveCell.Column.Header.Caption.StartsWith(mstrCurrentListingColPrefix) _
                Then
                If grdData.ActiveCell.Text.ToString.Equals(mstrNDValue) Then
                    lobjCurrentCol = mstCurrentDataSources.Find(Function(p) p.SourceName = grdData.ActiveCell.Column.Header.Caption)
                    If lobjCurrentCol IsNot Nothing Then
                        If lobjCurrentCol.SourceTypeCode = SourceTypeCode.UPD.ToString OrElse lobjCurrentCol.ESourceCode = DataSourceCode.DDCLEML.ToString Then
                            lblnCanExit = True
                        End If
                    ElseIf grdData.ActiveCell.Column.Header.Caption.StartsWith(mstrCurrentListingColPrefix) Then
                        lblnCanExit = True
                    End If
                    If lblnCanExit = False Then
                        e.Cancel = True
                    End If
                ElseIf Regex.Match(grdData.ActiveCell.Text.Replace(",", ""), "^([+-]?\d[+-]?)+$", RegexOptions.None).Success = False AndAlso grdData.ActiveCell.Text.Equals("") = False Then
                    e.Cancel = True
                    Exit Sub
                End If
            End If

            'Dim ldrCurrentCol As DataRow = Nothing

            'Check If the current column is a data source, run if it's not Nothing, because if there is an ND value in it, it will not be nothing as it has got value from the above code
            If lobjCurrentCol Is Nothing Then
                lobjCurrentCol = mstCurrentDataSources.Find(Function(p) p.SourceName = grdData.ActiveCell.Column.Header.Caption)
            End If

            If lobjCurrentCol Is Nothing Then
                'Check If the current column is a previous project
                If mstPreviousProjects.Find(Function(p) p.DeliveryListing = grdData.ActiveCell.Column.Header.Caption) Is Nothing AndAlso _
                    mstListingInformation.Find(Function(p) p.ListingName = grdData.ActiveCell.Column.Header.Caption.TrimStart(mstrFLCurrentListingPrefix.ToArray)) Is Nothing Then
                    Exit Sub
                Else
                    'If the current column is a previous project, then set the boolean variable to false
                    lblnIsFromDataSource = False
                End If
            End If
            lstrActiveCellValue = grdData.ActiveCell.Text.ToString
            lstrFormulaColName = grdData.ActiveCell.Column.Header.Caption
            'lstrFormulaColName += mstrFormulaColSuffix

            ''Check if the current column's Formula column exists
            If grdData.Rows.Band.Columns.Exists(lstrFormulaColName) Then
                'If it exists, then check if it does have the formulas
                If HasFormulas(lstrActiveCellValue) OrElse lstrActiveCellValue.Equals(mstrNDValue) Then
                    'If formula exists, then trim the = sign
                    SetAssociatedFormula(grdData.ActiveRow.GetCellValue("InvestorID"), grdData.ActiveRow.GetCellValue("FundID"), lstrFormulaColName, lstrActiveCellValue.TrimEnd("="))
                    'grdData.ActiveCell.Row.Cells(lstrFormulaColName).Value = lstrActiveCellValue.TrimEnd("=")
                Else
                    'Else keep it blank
                    SetAssociatedFormula(grdData.ActiveRow.GetCellValue("InvestorID"), grdData.ActiveRow.GetCellValue("FundID"), lstrFormulaColName, "")
                    'grdData.ActiveCell.Row.Cells(lstrFormulaColName).Value = ""
                End If
            End If
            'Check if the current column is a formula
            If mstEditableDataSourceNameCols.Contains(lstrFormulaColName) OrElse marrPreviousProjects.Contains(lstrFormulaColName) OrElse _
                grdData.ActiveCell.Column.Header.Caption.StartsWith(mstrCurrentListingColPrefix) Then
                If HasFormulas(grdData.ActiveCell.Text.ToString) OrElse grdData.ActiveCell.Text.ToString.Equals(mstrNDValue) Then
                    If lstrActiveCellValue.Equals(mstrNDValue) Then
                        grdData.ActiveCell.Value = mstrNDValue
                    Else
                        lstrCalculatedValue = CalculateValueFromFormula()
                        'Set the value of the cell
                        grdData.ActiveCell.Value = lstrCalculatedValue.ToString.TrimEnd("=")
                    End If
                    grdData.ActiveCell.Column.CellClickAction = CellClickAction.CellSelect
                End If
            End If
            'Update the Investor and Managed fund positions accordingly
            CalculateInvAndManagedFundPositions(InvestorPositionSources.OnCellChange, lblnIsFromDataSource, grdData.ActiveCell)
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            lobjCurrentCol = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' Runs after exiting the edit mode
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub grdData_AfterExitEditMode(ByVal sender As Object, ByVal e As System.EventArgs) Handles grdData.AfterExitEditMode
        'Check if the position value is blank, then set the date field to blank too.
        If mstEditableDataSourceNameCols.Contains(grdData.ActiveCell.Column.Header.Caption) Then
            SetSoureDateToBlank(grdData.ActiveRow, grdData.ActiveCell.Column.Header.Caption)
        End If
    End Sub

    ''' <summary>
    ''' To maintain the track of changes being made in the positions of current data sources and previous projects 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub grdData_AfterCellUpdate(ByVal sender As Object, ByVal e As Infragistics.Win.UltraWinGrid.CellEventArgs) Handles grdData.AfterCellUpdate
        'See if the current cell is editable source column or date column
        Dim lobjCurrentCol As CurrentDataSources = Nothing
        Dim lstrDataSourceColName As String = ""
        Dim lblnIsSumOfFunds As Boolean = False
        Dim lobjDataSourceChange As DataSourceChanges
        Dim lstrCalculatedValue As String
        Dim lobjDataChanges As New DataSourceChanges
        Dim lobjPPData As PreviousProjects = Nothing
        Dim lobjPreviousProjectChanges As FLPositionChanges
        Dim lobjPreviousDataChanges As New FLPositionChanges
        Dim lobjCurrentListingInfo As ListingInformation = Nothing
        Dim lblnIsFLCurrentCol As Boolean = False
        lblnIsFLCurrentCol = e.Cell.Column.Header.Caption.StartsWith(mstrFLCurrentListingPrefix)
        Try
            If mstEditableDataSourceNameCols.Contains(e.Cell.Column.Header.Caption) OrElse mstAllDataSourceDateCols.Contains(e.Cell.Column.Header.Caption) OrElse (e.Cell.Column.Header.Caption.StartsWith(mstrResearchColPrefix) AndAlso e.Cell.Column.Header.Caption.EndsWith(mstrSourceColSuffix)) Then
                'Dim ldrDataSource As DataRow = Nothing
                If mstEditableDataSourceNameCols.Contains(e.Cell.Column.Header.Caption) Then
                    lstrDataSourceColName = e.Cell.Column.Header.Caption
                    ''To reset Formula and SOF of the active row if user directly removes the content of the cell without going into Edit mode
                    ResetFormulaAndSOF(lstrDataSourceColName)
                    If HasFormulas(e.Cell.Row.GetCellValue(lstrDataSourceColName).ToString) Then Exit Sub
                ElseIf mstAllDataSourceDateCols.Contains(e.Cell.Column.Header.Caption) Then
                    lstrDataSourceColName = e.Cell.Column.Header.Caption.Substring(0, e.Cell.Column.Header.Caption.Length - mstrSourceDateColSuffix.Length)
                ElseIf (e.Cell.Column.Header.Caption.StartsWith(mstrResearchColPrefix) AndAlso e.Cell.Column.Header.Caption.EndsWith(mstrSourceColSuffix)) Then
                    lstrDataSourceColName = e.Cell.Column.Header.Caption.Substring(0, e.Cell.Column.Header.Caption.Length - mstrSourceColSuffix.Length)
                End If
                'SetSoureDateToBlank(grdData.ActiveRow, lstrDataSourceColName)
                'ldrDataSource = mdtCurrentDataSources.Rows.Find(lstrDataSourceColName)
                lobjCurrentCol = mstCurrentDataSources.Find(Function(p) p.SourceName = lstrDataSourceColName)
                If lobjCurrentCol Is Nothing Then Exit Sub
                'If the current data source is locked 
                If lobjCurrentCol.AccessStatus = SourceAccessbility.Locked.ToString AndAlso (lobjCurrentCol.SourceTypeCode = SourceTypeCode.DDI.ToString AndAlso _
                                                                                               (lobjCurrentCol.ESourceCode = DataSourceCode.DDCLEML.ToString OrElse _
                                                                                                lobjCurrentCol.ESourceCode = DataSourceCode.DDQUEST.ToString)) Then
                    If grdData.ActiveRow.GetCellValue(lobjCurrentCol.SourceName).ToString.Equals("") AndAlso _
                                                      grdData.ActiveRow.GetCellValue(lobjCurrentCol.SourceDate).ToString.Equals("") = False Then
                        grdData.ActiveRow.Cells(lobjCurrentCol.SourceDate).Value = DBNull.Value
                    End If
                End If
                ''''''''''''Starts: Temporarily Commented'''''''''''''''''''''''
                ' ''Check if the current source is Research and if the value is not nothing, then user has to give specify date and the Source
                If (lobjCurrentCol.AccessStatus = SourceAccessbility.Locked.ToString OrElse menmScreenType = DataHubScreenType.FinalizeList) Then
                    SetSourceData(e.Cell, lobjCurrentCol)
                End If

                ' ''''''''''''Ends: Temporarily Commented'''''''''''''''''''''''

                'Check if the current cell is already changed and is tracked in the table
                lobjDataSourceChange = mstDataSourceChanges.Find(Function(p) p.EntityID = lobjCurrentCol.EntityID And _
                                                                                              p.InvestorID = e.Cell.Row.GetCellValue("InvestorID") And _
                                                                                              p.FundID = e.Cell.Row.GetCellValue("FundID"))
                'ldrChangedRow = mdtDataSourceChanges.Rows.Find(New Object() {ldrDataSource("EntityID"), e.Cell.Row.GetCellValue(e.Cell.Row.Cells("InvestorID").Column), e.Cell.Row.GetCellValue(e.Cell.Row.Cells("LinkID").Column)})
                'If not, add a new row
                If lobjDataSourceChange Is Nothing Then
                    lobjDataChanges.ListingID = lobjCurrentCol.ListingID
                    lobjDataChanges.EntityID = lobjCurrentCol.EntityID
                    lobjDataChanges.InvestorID = e.Cell.Row.GetCellValue("InvestorID")
                    lobjDataChanges.LinkID = e.Cell.Row.GetCellValue("LinkID")
                    lobjDataChanges.FundID = e.Cell.Row.GetCellValue("FundID")

                    If e.Cell.Row.GetCellValue(lstrDataSourceColName).ToString.Equals("") OrElse e.Cell.Row.GetCellValue(lstrDataSourceColName).ToString.Equals(mstrNDValue) Then
                        lobjDataChanges.Position = Nothing
                    Else
                        If HasFormulas(e.Cell.Row.GetCellValue(lstrDataSourceColName)) Then
                            lstrCalculatedValue = CalculateValueFromFormula()
                            lobjDataSourceChange.Position = Convert.ToInt64(lstrCalculatedValue.TrimEnd("=").Replace(",", ""))
                        Else
                            lobjDataChanges.Position = Convert.ToInt64(e.Cell.Row.GetCellValue(lstrDataSourceColName).ToString.Replace(",", ""))
                        End If
                    End If

                    If e.Cell.Row.Band.Columns.Exists(lstrDataSourceColName + mstrSourceDateColSuffix) Then
                        If e.Cell.Row.GetCellValue(lstrDataSourceColName + mstrSourceDateColSuffix) Is DBNull.Value Then
                            lobjDataChanges.SourceDate = Nothing
                        Else
                            lobjDataChanges.SourceDate = Convert.ToDateTime(e.Cell.Row.GetCellValue(lstrDataSourceColName + mstrSourceDateColSuffix))
                        End If
                    End If

                    If e.Cell.Row.GetCellValue("FundID") <> 0 Then
                        lblnIsSumOfFunds = False
                    Else
                        lblnIsSumOfFunds = CheckSumOfFunds(e.Cell.Row.GetCellValue("InvestorID"), lstrDataSourceColName, True, True)
                    End If

                    lobjDataChanges.IsSumOfFunds = lblnIsSumOfFunds

                    lobjDataChanges.Formula = GetFormula(e.Cell.Row.GetCellValue("InvestorID"), e.Cell.Row.GetCellValue("FundID"), e.Cell.Row.GetCellValue("LinkID"), lstrDataSourceColName, True)

                    If lobjCurrentCol.SourceTypeCode = SourceTypeCode.RSH.ToString Then
                        lobjDataChanges.ClientSpecificSource = e.Cell.Row.GetCellValue(lstrDataSourceColName + mstrClientSpecificSourceColSuffix).ToString
                        lobjDataChanges.GenericSource = e.Cell.Row.GetCellValue(lstrDataSourceColName + mstrGenericSourceColSuffix).ToString
                    Else
                        lobjDataChanges.ClientSpecificSource = ""
                        lobjDataChanges.GenericSource = ""
                    End If

                    mstDataSourceChanges.Add(lobjDataChanges)
                Else
                    'If its not then update the data in the same row
                    If e.Cell.Row.GetCellValue(lstrDataSourceColName).ToString.Equals("") OrElse e.Cell.Row.GetCellValue(lstrDataSourceColName).ToString.Equals(mstrNDValue) Then
                        lobjDataSourceChange.Position = Nothing
                    Else
                        If HasFormulas(e.Cell.Row.GetCellValue(lstrDataSourceColName)) Then
                            lstrCalculatedValue = CalculateValueFromFormula()
                            lobjDataSourceChange.Position = Convert.ToInt64(lstrCalculatedValue.TrimEnd("=").Replace(",", ""))
                        Else
                            lobjDataSourceChange.Position = Convert.ToInt64(e.Cell.Row.GetCellValue(lstrDataSourceColName).ToString.Replace(",", ""))
                        End If
                    End If

                    If e.Cell.Row.Band.Columns.Exists(lstrDataSourceColName + mstrSourceDateColSuffix) Then
                        If e.Cell.Row.GetCellValue(lstrDataSourceColName + mstrSourceDateColSuffix) Is DBNull.Value Then
                            lobjDataSourceChange.SourceDate = Nothing
                        Else
                            lobjDataSourceChange.SourceDate = Convert.ToDateTime(e.Cell.Row.GetCellValue(lstrDataSourceColName + mstrSourceDateColSuffix))
                        End If
                    End If

                    If e.Cell.Row.GetCellValue("FundID") <> 0 Then
                        lblnIsSumOfFunds = False
                    Else
                        lblnIsSumOfFunds = CheckSumOfFunds(e.Cell.Row.GetCellValue("InvestorID"), lstrDataSourceColName, True, True)
                    End If
                    'lblnIsSumOfFunds = True
                    'If e.Cell.Row.GetCellValue(mstrSOFColPrefix + lstrDataSourceColName) IsNot DBNull.Value Then
                    '    lblnIsSumOfFunds = e.Cell.Row.GetCellValue(mstrSOFColPrefix + lstrDataSourceColName)
                    'End If
                    lobjDataSourceChange.IsSumOfFunds = lblnIsSumOfFunds
                    lobjDataSourceChange.Formula = GetFormula(e.Cell.Row.GetCellValue("InvestorID"), e.Cell.Row.GetCellValue("FundID"), e.Cell.Row.GetCellValue("LinkID"), lstrDataSourceColName, True)
                    'lobjDataSourceChange.Formula = e.Cell.Row.GetCellValue(lstrDataSourceColName + mstrFormulaColSuffix).ToString
                    If lobjCurrentCol.SourceTypeCode = SourceTypeCode.RSH.ToString Then
                        lobjDataChanges.ClientSpecificSource = e.Cell.Row.GetCellValue(lstrDataSourceColName + mstrClientSpecificSourceColSuffix).ToString
                        lobjDataChanges.GenericSource = e.Cell.Row.GetCellValue(lstrDataSourceColName + mstrGenericSourceColSuffix).ToString
                    Else
                        lobjDataChanges.ClientSpecificSource = ""
                        lobjDataChanges.GenericSource = ""
                    End If
                End If
                'Check if the current cell is a previous project cell
            ElseIf marrPreviousProjects.Contains(e.Cell.Column.Header.Caption) OrElse lblnIsFLCurrentCol Then
                ''To reset Formula and SOF of the active row if user directly removes the content of the cell without going into Edit mode
                ResetFormulaAndSOF(e.Cell.Column.Header.Caption)
                Dim lintSelectedListingID As Integer
                If lblnIsFLCurrentCol Then
                    lobjCurrentListingInfo = mstListingInformation.Find(Function(p) p.ListingName = e.Cell.Column.Header.Caption.TrimStart(mstrFLCurrentListingPrefix.ToArray))
                    lintSelectedListingID = lobjCurrentListingInfo.ListingID
                Else
                    'lstrListingColumn = e.Cell.Column.Header.Caption
                    lobjPPData = mstPreviousProjects.Find(Function(p) p.DeliveryListing = e.Cell.Column.Header.Caption)
                    If lobjPPData Is Nothing Then Exit Sub
                    lintSelectedListingID = lobjPPData.ListingID
                    'Keeping track if there are any changes in the previous project's positions, so that it can be used to determine whether a Sort is required or not
                    If lobjPPData.DeliveryListing.Equals(mstrDeliveryListingToSort) Then
                        mblnAnyChangesInLastProject = True
                    End If
                End If
                lobjPreviousProjectChanges = mstPreviousProjectChanges.Find(Function(p) p.ListingID = lintSelectedListingID And _
                                                                                p.InvestorID = e.Cell.Row.GetCellValue("InvestorID") And _
                                                                                p.FundID = e.Cell.Row.GetCellValue("FundID"))
                lstrCalculatedValue = String.Empty
                'Check if the current cell is already changed and is tracked in the table
                If lobjPreviousProjectChanges Is Nothing Then
                    'Dim lobjPreviousDataChanges As New PreviousProjectChanges
                    'ldrPositionData = mdtPreviousProjectChanges.NewRow
                    lobjPreviousDataChanges.InvestorID = e.Cell.Row.GetCellValue("InvestorID")
                    lobjPreviousDataChanges.FundID = e.Cell.Row.GetCellValue("FundID")
                    lobjPreviousDataChanges.LinkID = e.Cell.Row.GetCellValue("LinkID")
                    If e.Cell.Row.GetCellValue(e.Cell.Column.Header.Caption).ToString.Equals("") OrElse e.Cell.Row.GetCellValue(e.Cell.Column.Header.Caption).ToString.Equals(mstrNDValue) Then
                        lobjPreviousDataChanges.Position = Nothing
                    Else
                        If HasFormulas(e.Cell.Row.GetCellValue(e.Cell.Column.Header.Caption)) Then
                            lstrCalculatedValue = CalculateValueFromFormula()
                            lobjPreviousDataChanges.Position = Convert.ToInt64(lstrCalculatedValue.TrimEnd("=").Replace(",", ""))
                        Else
                            lobjPreviousDataChanges.Position = Convert.ToInt64(e.Cell.Row.GetCellValue(e.Cell.Column.Header.Caption).ToString.Replace(",", ""))
                        End If
                    End If
                    If e.Cell.Row.GetCellValue("LinkID") = 0 Then
                        'lobjPreviousDataChanges.IsSumOfFunds = e.Cell.Row.GetCellValue(mstrSOFColPrefix + e.Cell.Column.Header.Caption)
                        lobjPreviousDataChanges.IsSumOfFunds = CheckSumOfFunds(e.Cell.Row.GetCellValue("InvestorID"), e.Cell.Column.Header.Caption, True, True)
                    End If
                    lobjPreviousDataChanges.Formula = GetFormula(e.Cell.Row.GetCellValue("InvestorID"), e.Cell.Row.GetCellValue("FundID"), e.Cell.Row.GetCellValue("LinkID"), e.Cell.Column.Header.Caption, True)
                    'lobjPreviousDataChanges.Formula = e.Cell.Row.GetCellValue(e.Cell.Column.Header.Caption + mstrFormulaColSuffix).ToString
                    lobjPreviousDataChanges.ListingID = lintSelectedListingID
                    mstPreviousProjectChanges.Add(lobjPreviousDataChanges)
                Else
                    'If its not then update the data in the same row
                    If e.Cell.Row.GetCellValue(e.Cell.Column.Header.Caption).ToString.Equals("") OrElse e.Cell.Row.GetCellValue(e.Cell.Column.Header.Caption).ToString.Equals(mstrNDValue) Then
                        lobjPreviousProjectChanges.Position = Nothing
                    Else
                        If HasFormulas(e.Cell.Row.GetCellValue(e.Cell.Column.Header.Caption)) Then
                            lstrCalculatedValue = CalculateValueFromFormula()
                            'Set the value of the cell
                            lobjPreviousProjectChanges.Position = Convert.ToInt64(lstrCalculatedValue.TrimEnd("=").Replace(",", ""))
                        Else
                            lobjPreviousProjectChanges.Position = Convert.ToInt64(e.Cell.Row.GetCellValue(e.Cell.Column.Header.Caption).ToString.Replace(",", ""))
                        End If
                    End If
                    If e.Cell.Row.GetCellValue("LinkID") = 0 Then
                        lobjPreviousProjectChanges.IsSumOfFunds = CheckSumOfFunds(e.Cell.Row.GetCellValue("InvestorID"), e.Cell.Column.Header.Caption, True, True)
                        'lobjPreviousProjectChanges.IsSumOfFunds = e.Cell.Row.GetCellValue(mstrSOFColPrefix + e.Cell.Column.Header.Caption)
                    End If
                    lobjPreviousProjectChanges.Formula = GetFormula(e.Cell.Row.GetCellValue("InvestorID"), e.Cell.Row.GetCellValue("FundID"), e.Cell.Row.GetCellValue("LinkID"), e.Cell.Column.Header.Caption, True)
                    'lobjPreviousProjectChanges.Formula = e.Cell.Row.GetCellValue(e.Cell.Column.Header.Caption + mstrFormulaColSuffix).ToString
                End If
            End If
            'If the changes are made in a Master record, they have to be saved immediately
            If e.Cell.Row.GetCellValue("IsMasterDB").ToString <> String.Empty Then
                If e.Cell.Row.GetCellValue("IsMasterDB") = True Then
                    SaveData(True, False)
                    grdData.UpdateData()
                    grdData.EventManager.SetEnabled(Infragistics.Win.UltraWinGrid.GridEventIds.AfterCellUpdate, False)
                    e.Cell.Row.Cells("IsMasterDB").Value = False
                    If e.Cell.Row.GetCellValue("FundID") = 0 Then
                        e.Cell.Row.CellAppearance = grdData.DisplayLayout.Appearances("GridInvAddedAppearance")
                    Else
                        e.Cell.Row.CellAppearance = grdData.DisplayLayout.Appearances("GridForeColor")
                    End If
                End If
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            grdData.EventManager.SetEnabled(Infragistics.Win.UltraWinGrid.GridEventIds.AfterCellUpdate, True)
            lobjPreviousProjectChanges = Nothing
            lobjPreviousDataChanges = Nothing
            lobjDataSourceChange = Nothing
            lobjPPData = Nothing
            lobjCurrentCol = Nothing
            lobjDataChanges = Nothing
            lobjCurrentListingInfo = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' To set the source of data
    ''' </summary>
    ''' <param name="lcell"></param>
    ''' <param name="lobjCurrentCol"></param>
    ''' <remarks></remarks>
    Private Sub SetSourceData(ByRef lcell As UltraGridCell, ByVal lobjCurrentCol As CurrentDataSources)
        Dim lSourceData As New SourceData
        Try
            If lobjCurrentCol.SourceTypeCode = SourceTypeCode.RSH.ToString Then
                If mstEditableDataSourceNameCols.Contains(lcell.Column.Header.Caption) Then
                    If lcell.Row.GetCellValue(lcell.Column.Header.Caption).ToString.Equals("") Then
                        lcell.Row.Cells(lcell.Column.Header.Caption + mstrClientSpecificSourceColSuffix).Value = ""
                        lcell.Row.Cells(lcell.Column.Header.Caption + mstrGenericSourceColSuffix).Value = ""
                        lSourceData.mstrClientSpecificSource = ""
                        lSourceData.mstrGenericSource = ""
                    Else
                        lSourceData.ShowDialog()
                        mblsSourceData = True
                        If lSourceData.mblnSaved Then
                            lcell.Row.Cells(lcell.Column.Header.Caption + mstrSourceDateColSuffix).Value = lSourceData.mdateSourceDate
                            If lcell.Band.Columns.Exists(lcell.Column.Header.Caption + mstrSourceColSuffix) Then
                                If lSourceData.mstrClientSpecificSource <> String.Empty Then
                                    lcell.Row.Cells(lcell.Column.Header.Caption + mstrSourceColSuffix).Value = lSourceData.mstrClientSpecificSource
                                Else
                                    lcell.Row.Cells(lcell.Column.Header.Caption + mstrSourceColSuffix).Value = lSourceData.mstrGenericSource
                                End If
                            End If
                            If lcell.Band.Columns.Exists(lcell.Column.Header.Caption + mstrClientSpecificSourceColSuffix) AndAlso lcell.Band.Columns.Exists(lcell.Column.Header.Caption + mstrGenericSourceColSuffix) Then
                                lcell.Row.Cells(lcell.Column.Header.Caption + mstrClientSpecificSourceColSuffix).Value = lSourceData.mstrClientSpecificSource
                                lcell.Row.Cells(lcell.Column.Header.Caption + mstrGenericSourceColSuffix).Value = lSourceData.mstrGenericSource
                            End If
                        Else
                            Exit Sub
                        End If
                    End If
                End If
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            lSourceData = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' Function CalculateValueFromFormula
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function CalculateValueFromFormula() As String
        Dim lstrActiveCellValue As String = grdData.ActiveCell.Text.ToString
        If grdData.ActiveCell.Text.ToString.Length = 0 Then
            Return "0"
        End If
        svalue = 0
        Dim r As Number = New Number
        'Get the calculated value in an integer variable
        If Not grdData.ActiveCell.Text.EndsWith("=") Then
            lstrActiveCellValue = lstrActiveCellValue.Insert(grdData.ActiveCell.Text.Length, "=")
        End If
        toeval = lstrActiveCellValue
        eval1(r)
        Return r.tostring
    End Function

    ''' <summary>
    ''' To set the cell click action
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub grdData_BeforeCellDeactivate(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles grdData.BeforeCellDeactivate
        'Dim lobjCurrentCol As CurrentDataSources = Nothing
        'Dim lstrDataSourceColName As String
        'lstrDataSourceColName = grdData.ActiveCell.Column.Header.Caption
        grdData.ActiveCell.Column.CellClickAction = CellClickAction.CellSelect
        'If menmScreenType = DataHubScreenType.DataEntry AndAlso mstAllDataSourceNameCols(lstrDataSourceColName) Then
        '    lobjCurrentCol = mstCurrentDataSources.Find(Function(p) p.SourceName = lstrDataSourceColName)
        '    If lobjCurrentCol Is Nothing Then Exit Sub
        '    If lobjCurrentCol.AccessStatus <> SourceAccessbility.Locked.ToString Then
        '        grdData.ActiveCell.Activation = Activation.ActivateOnly
        '    End If
        'End If
    End Sub

    ''' <summary>
    ''' Like excel, when double click is performed, turn the cell to edit mode
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub grdData_DoubleClickCell(ByVal sender As Object, ByVal e As Infragistics.Win.UltraWinGrid.DoubleClickCellEventArgs) Handles grdData.DoubleClickCell
        If (mstEditableDataSourceNameCols.Contains(e.Cell.Column.Header.Caption) OrElse marrPreviousProjects.Contains(e.Cell.Column.Header.Caption) OrElse _
            e.Cell.Column.Header.Caption.StartsWith(mstrFLCurrentListingPrefix)) AndAlso mstResearchDateCols.Contains(e.Cell.Column.Header.Caption) = False Then
            SetCellInEditMode(e.Cell, True)
        End If
    End Sub

    ''' <summary>
    ''' To show the tooltip
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub grdData_MouseEnterElement(ByVal sender As Object, ByVal e As Infragistics.Win.UIElementEventArgs) Handles grdData.MouseEnterElement
        'To show the tooltip once on mouse hovering on Notes column
        Dim tipInfo As Infragistics.Win.UltraWinToolTip.UltraToolTipInfo
        Dim lColHeader As ColumnHeader
        Dim acell As UltraGridCell
        Dim lobjCurrentDataSources As CurrentDataSources = Nothing
        Dim lobjListingInformation As ListingInformation = Nothing
        Dim lstrUserNames As String = ""
        Try
            acell = e.Element.GetContext(GetType(Infragistics.Win.UltraWinGrid.UltraGridCell))
            If Not acell Is Nothing Then
                If acell.Column.Header.Caption = "Notes" Then
                    tipInfo = New Infragistics.Win.UltraWinToolTip.UltraToolTipInfo(MessageManager.GetMessage(DBResult.DE_NOTES_SHORTCUT_1.ToString) + Environment.NewLine + MessageManager.GetMessage(DBResult.DE_NOTES_SHORTCUT_2.ToString) + Environment.NewLine + MessageManager.GetMessage(DBResult.DE_NOTES_SHORTCUT_3.ToString), ToolTipImage.Info, "Shortcut", DefaultableBoolean.True)
                    tipInfo.Appearance.BackColor = grdData.DisplayLayout.Appearances("ToolTipInfo").BackColor  'Color.FromArgb(246, 214, 115)
                    UltraToolTipManager1.Enabled = True
                    UltraToolTipManager1.SetUltraToolTip(sender, tipInfo)
                    UltraToolTipManager1.ShowToolTip(sender)
                    Exit Sub
                End If
            End If

            'Get the currently hovered over Data source and show the User names who have ever worked on it
            lColHeader = e.Element.GetContext(GetType(Infragistics.Win.UltraWinGrid.ColumnHeader))
            If Not lColHeader Is Nothing Then
                lobjCurrentDataSources = mstCurrentDataSources.Find(Function(p) p.SourceName = lColHeader.Caption)
                If lobjCurrentDataSources Is Nothing Then
                    If lColHeader.Caption.Length > mstrSourceDateColSuffix.Length Then
                        lobjCurrentDataSources = mstCurrentDataSources.Find(Function(p) p.SourceDate = lColHeader.Caption)
                    End If
                End If
                If lobjCurrentDataSources Is Nothing Then
                    lobjListingInformation = mstListingInformation.Find(Function(p) p.CurrentListingName = lColHeader.Caption)
                End If
                If lobjCurrentDataSources IsNot Nothing Then
                    lstrUserNames = mclsDataHubManager.GetDataEntityAccessHistory(lobjCurrentDataSources.EntityID, -1, False)
                    If lstrUserNames.Equals("") And Not lobjCurrentDataSources.IsND And Not lobjCurrentDataSources.IsNIL Then
                        UltraToolTipManager1.HideToolTip()
                        Exit Sub
                    End If

                    If lobjCurrentDataSources.IsND Then
                        ShowToolTip(sender, MessageManager.GetMessage(DBResult.ND.ToString))
                        Exit Sub
                    ElseIf lobjCurrentDataSources.IsNIL Then
                        ShowToolTip(sender, MessageManager.GetMessage(DBResult.NIL.ToString))
                        Exit Sub
                    End If
                ElseIf lobjListingInformation IsNot Nothing Then
                    lstrUserNames = mclsDataHubManager.GetDataEntityAccessHistory(-1, lobjListingInformation.ListingID, True)
                    If lstrUserNames.Equals("") Then
                        UltraToolTipManager1.HideToolTip()
                        Exit Sub
                    End If
                End If
                If lobjCurrentDataSources IsNot Nothing OrElse lobjListingInformation IsNot Nothing Then
                    tipInfo = New Infragistics.Win.UltraWinToolTip.UltraToolTipInfo(lstrUserNames, ToolTipImage.Info, "History", DefaultableBoolean.True)
                    tipInfo.Appearance.BackColor = grdData.DisplayLayout.Appearances("ToolTipInfo").BackColor  'Color.FromArgb(246, 214, 115)
                    UltraToolTipManager1.Enabled = True
                    UltraToolTipManager1.SetUltraToolTip(sender, tipInfo)
                    UltraToolTipManager1.ShowToolTip(sender)
                    Exit Sub
                End If
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            tipInfo = Nothing
            lColHeader = Nothing
            acell = Nothing
            lobjCurrentDataSources = Nothing
            lobjListingInformation = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' Disable the Tooltip managed once the mouse leaves the grid
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub grdData_MouseLeaveElement(ByVal sender As System.Object, ByVal e As Infragistics.Win.UIElementEventArgs) Handles grdData.MouseLeaveElement
        UltraToolTipManager1.Enabled = False
    End Sub

    ''' <summary>
    ''' To perform the keyboard operations on the grid
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub grdData_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles grdData.KeyDown
        Dim lobjCurrentCol As CurrentDataSources = Nothing
        Dim lblnIsFromDataSource As Boolean
        Dim lintActiveRowIndex As Integer
        Dim lblnIsSumOfFunds As Boolean
        Dim lfrmNotes As Notes = Nothing
        Dim lstrInvestorFundIDData As String
        Dim larrExcludingCols() As String
        Dim larrKeyCols() As String = {""}
        Dim lenmAction As UltraGridAction
        Dim strColumnName As String = ""
        Dim strCurrentColumnName As String = ""
        Dim strCurrentColumn As String = ""
        Dim strNextColumn As String = ""
        Dim intNextColumn As Integer
        Dim lobjCopiedCol As CurrentDataSources = Nothing
        Try
            If menmScreenType = DataHubScreenType.FinalizeList Then
                If e.KeyCode >= Keys.A And e.KeyCode <= Keys.Z AndAlso e.Modifiers <> Keys.Control Then
                    If grdData.Selected.Rows.Count <= 1 Then
                        e.SuppressKeyPress = True
                        If grdData.ActiveCell Is Nothing Or grdData.Selected.Cells.Count = 0 Then Exit Sub
                        If grdData.ActiveCell IsNot Nothing Then
                            If Not grdData.ActiveCell.Column.Header.Caption.StartsWith(mstrFLCurrentListingPrefix) Then Exit Sub
                            strCurrentColumnName = grdData.ActiveCell.Column.Header.Caption
                        End If

                        If grdData.Selected.Cells.Count > 0 Then
                            For Each cell As UltraGridCell In grdData.Selected.Cells
                                If Not cell.Column.Header.Caption.StartsWith(mstrFLCurrentListingPrefix) Then Exit Sub
                            Next
                            If strCurrentColumnName = String.Empty Then
                                strCurrentColumnName = grdData.Selected.Cells(0).Column.Header.Caption
                            End If
                        End If

                        Dim lobjListingInformation As ListingInformation = Nothing
                        Dim lstrUpdatedValue As String = ""
                        Dim lstColumnSameShortcut As New List(Of String)
                        lobjListingInformation = mstListingInformation.Find(Function(p) p.ListingName = strCurrentColumnName.TrimStart(mstrFLCurrentListingPrefix.ToArray))
                        If lobjListingInformation IsNot Nothing Then
                            lobjCopiedCol = mstCurrentDataSources.Find(Function(p) p.AlphaShortcut = e.KeyCode.ToString)

                            If lobjCopiedCol Is Nothing Then
                                If mdicShortCut IsNot Nothing Then
                                    For Each item In mdicShortCut
                                        'types.FirstOrDefault(x => x.Value == "one")
                                        If item.Value.ToString = e.KeyCode.ToString Then
                                            lstColumnSameShortcut.Add(item.Key.ToString)
                                        End If
                                    Next
                                    If lstColumnSameShortcut.Count > 0 Then
                                        strColumnName = GetColumnNameShortcut(lstColumnSameShortcut, strCurrentColumnName)
                                    End If
                                End If
                            Else
                                strColumnName = lobjCopiedCol.SourceName
                            End If
                            If strColumnName <> String.Empty Then

                                If e.KeyCode = Keys.S Then
                                    mclsDataHubManager.GetCalculatedSuggestions(mintClientID, mintProjectID, mintPreviousProjectID, "", Nothing, lobjListingInformation.ListingID, _
                                                                                grdData.ActiveCell.Row.GetCellValue("InvestorID"), _
                                                                                grdData.ActiveCell.Row.GetCellValue("LinkID"), lstrUpdatedValue, False)
                                    If lstrUpdatedValue IsNot Nothing Then
                                        grdData.ActiveCell.Value = lstrUpdatedValue
                                    Else
                                        grdData.ActiveCell.Value = DBNull.Value
                                    End If
                                ElseIf e.KeyCode = Keys.A Then
                                    mclsDataHubManager.GetCurrentListingValue(mintProjectID, "", Nothing, lobjListingInformation.ListingID, _
                                                                            grdData.ActiveCell.Row.GetCellValue("InvestorID"), _
                                                                            grdData.ActiveCell.Row.GetCellValue("LinkID"), lstrUpdatedValue)
                                    If lstrUpdatedValue IsNot Nothing Then
                                        grdData.ActiveCell.Value = lstrUpdatedValue
                                    Else
                                        grdData.ActiveCell.Value = DBNull.Value
                                    End If
                                Else
                                    If grdData.DisplayLayout.Bands(0).Columns.Exists(strColumnName) Then
                                        PasteInCurrentColumn(strColumnName)
                                        'PasteCopiedData(strColumnName, strCurrentColumnName)
                                    End If
                                End If
                                'grdData.ActiveCell.Value = lstrUpdatedValue
                            End If
                        End If
                    End If
                End If
            End If
            If e.Modifiers = Keys.Control Then
                'To access the Notes form for the currently selected row, press Ctrl+D
                If e.KeyCode = Keys.D Then
                    If grdData.Selected.Rows.Count > 1 Then
                        larrExcludingCols = GetExcludingColsForNotes()
                        lfrmNotes = New Notes
                        lfrmNotes.mintProjectID = mintProjectID
                        lfrmNotes.menmScreenType = menmScreenType
                        'Find the Investor and FundID's of the selected rows
                        lstrInvestorFundIDData = CommonCLL.GetXMlFromUltraGrid(grdData, larrExcludingCols, larrKeyCols, False)
                        lfrmNotes.mstrInvestorFundIDs = lstrInvestorFundIDData
                        lfrmNotes.mintCurrentInvestorID = grdData.ActiveRow.GetCellValue("InvestorID")
                        lfrmNotes.mintCurrentLinkID = grdData.ActiveRow.GetCellValue("LinkID")
                        lfrmNotes.mstrDENotesDefaultText = mstrDENotesDefaultText
                        lfrmNotes.mstrFLNotesDefaultText = mstrFLNotesDefaultText
                        lfrmNotes.mstCurrentDataSources = mstCurrentDataSources
                        lfrmNotes.ShowDialog()
                        'If Notes' saved is successful, then Load the latest Notes in the corresponding text boxes
                        If lfrmNotes.mblnIsSavedSuccess Then
                            LoadNotes()
                            If lfrmNotes.mstNotesStatus IsNot Nothing Then
                                UpdateNotesStatus(lfrmNotes.mstNotesStatus)
                            End If
                            'grdData.ActiveRow.Cells("Notes").Value = lfrmNotes.mstrNotes
                        End If
                    Else
                        'If selected row count=0 then show the Notes section
                        If spcDataHub.Panel2Collapsed Then
                            spcDataHub.Panel2Collapsed = False
                            If menmScreenType = DataHubScreenType.DataEntry Then
                                SetDENotesText(txtDENotes)
                            ElseIf menmScreenType = DataHubScreenType.FinalizeList Then
                                SetDENotesText(txtFLNotes)
                            End If
                        End If
                        rdbDECurrentNotes.Checked = True
                        rdbFLCurrentNotes.Checked = True
                        If menmScreenType = DataHubScreenType.DataEntry Then
                            txtDENotes.Focus()
                        ElseIf menmScreenType = DataHubScreenType.FinalizeList Then
                            txtFLNotes.Focus()
                        End If
                    End If
                    'Ctrl+A is used to make the selected Investor/Entity row a SumofFunds
                ElseIf e.KeyCode = Keys.A Then
                    If mstAllDataSourceNameCols.Contains(grdData.ActiveCell.Column.Header.Caption) = False AndAlso _
                        marrPreviousProjects.Contains(grdData.ActiveCell.Column.Header.Caption) = False AndAlso _
                        grdData.ActiveCell.Column.Header.Caption.TrimStart(mstrFLCurrentListingPrefix.ToArray) Is Nothing Then Exit Sub
                    lblnIsFromDataSource = False
                    lintActiveRowIndex = grdData.ActiveCell.Row.Index
                    lblnIsSumOfFunds = True
                    'Check if the selected cell is a data source and an Investor
                    lblnIsFromDataSource = mstAllDataSourceNameCols.Contains(grdData.ActiveCell.Column.Header.Caption)
                    If grdData.Rows(lintActiveRowIndex).GetCellValue("LinkID") = 0 Then
                        lblnIsSumOfFunds = CheckSumOfFunds(grdData.Rows(lintActiveRowIndex).GetCellValue("InvestorID"), grdData.ActiveCell.Column.Header.Caption, True, False)
                        'lblnIsSumOfFunds = CommonCLL.IsNullToTrueForBool(grdData.Rows(lintActiveRowIndex).GetCellValue(mstrSOFColPrefix + grdData.ActiveCell.Column.Header.Caption))
                        If lblnIsSumOfFunds = False Then
                            'Update the Investor and Managed fund positions accordingly
                            CalculateInvAndManagedFundPositions(InvestorPositionSources.RevertToSumOfFunds, lblnIsFromDataSource, grdData.ActiveCell)
                        End If
                    End If
                    'Focus on the Investor text box
                ElseIf e.KeyCode = Keys.F Then
                    txtInvestor.Focus()
                End If
            ElseIf e.Modifiers = Keys.None Then
                ''Perform action needed to move cursor
                'To move on to the next cell in the grid
                If e.KeyCode = Keys.Enter Then
                    lenmAction = UltraGridAction.BelowCell
                    If grdData.ActiveCell IsNot Nothing Then
                        lobjCurrentCol = mstCurrentDataSources.Find(Function(p) p.SourceName = grdData.ActiveCell.Column.Header.Caption)
                        If lobjCurrentCol IsNot Nothing Then
                            'If the current cell is a locked column then move on to Next, otherwise below
                            If lobjCurrentCol.AccessStatus = SourceAccessbility.Locked.ToString AndAlso (lobjCurrentCol.SourceTypeCode = SourceTypeCode.DDI.ToString AndAlso _
                                                                                               (lobjCurrentCol.ESourceCode = DataSourceCode.DDCLEML.ToString OrElse lobjCurrentCol.ESourceCode = DataSourceCode.DDQUEST.ToString)) Then
                                If grdData.ActiveCell.Value.ToString.Equals("") = False Then
                                    lenmAction = UltraGridAction.NextCell
                                End If
                            End If
                        End If
                        If grdData.ActiveRow.VisibleIndex = grdData.Rows.VisibleRowCount - 1 Then
                            grdData.PerformAction(UltraGridAction.NextCell, False, False)
                        Else
                            grdData.PerformAction(lenmAction, False, False)
                        End If
                    End If
                    'Set the cell in Edit mode on press of F2
                ElseIf e.KeyCode = Keys.F2 Then
                    SetCellInEditMode(grdData.ActiveCell, False)
                    'Cancel out Cut operation on Escape
                ElseIf e.KeyCode = Keys.Escape Then
                    CancelOutCutOperation()
                ElseIf e.KeyCode = Keys.Delete Then
                    If grdData.Selected.Rows.Count > 0 Then
                        e.SuppressKeyPress = True
                    End If
                    'If Not e.KeyCode Like "[A-Za-z]" Then e.Handled = True
                    'ElseIf e.KeyCode = Keys.Tab Then
                    '    e.SuppressKeyPress = True
                    'grdData.ActiveCell = grdData.ActiveCell.
                    'intNextColumn = grdData.ActiveCell.Column.Header.VisiblePosition
                    'If grdData.DisplayLayout.Bands(0).Columns.Exists(grdData.DisplayLayout.Bands(0).Columns(intNextColumn + 1).Header.Caption) Then
                    '    strNextColumn = grdData.DisplayLayout.Bands(0).Columns(intNextColumn + 1).Header.Caption
                    '    grdData.Rows(grdData.ActiveCell.Row.Index).Cells(strNextColumn).Activate()
                    'End If
                End If
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            lenmAction = Nothing
            lfrmNotes = Nothing
            lobjCurrentCol = Nothing
        End Try
    End Sub

    Private Function GetColumnNameShortcut(ByVal lstSameShortcutColumns As List(Of String), ByVal lstrCurrentColumn As String) As String
        Dim lstrColumnName As String = String.Empty
        Dim literal As String = String.Empty
        Dim strListingName As String = String.Empty
        strListingName = lstrCurrentColumn.Substring(mstrCurrentListingColPrefix.Length, lstrCurrentColumn.Length - mstrCurrentListingColPrefix.Length)
        For Each strShortcut As String In lstSameShortcutColumns
            If strShortcut.Contains(strListingName) Then
                lstrColumnName = strShortcut
            End If
        Next
        Return lstrColumnName
    End Function

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub grdData_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles grdData.KeyPress
        Dim grid As UltraGrid = Nothing
        Dim activeCell As UltraGridCell = Nothing
        Dim editor As EmbeddableEditorBase
        If TypeOf sender Is UltraGrid Then
            grid = DirectCast(sender, UltraGrid)
        End If

        If Not grid Is Nothing Then
            activeCell = grid.ActiveCell
        End If

        ' if there is an active cell, its not in edit mode and can enter edit mode
        If Not activeCell Is Nothing AndAlso Not activeCell.IsInEditMode AndAlso activeCell.CanEnterEditMode Then
            ' if the character is not a control character
            If Char.IsControl(e.KeyChar) = False Then
                ' try to put cell into edit mode
                grid.PerformAction(UltraGridAction.EnterEditMode)

                ' if this cell is still active and it is in edit mode...
                If grid.ActiveCell Is activeCell AndAlso activeCell.IsInEditMode Then
                    ' get its editor
                    editor = Me.grdData.ActiveCell.EditorResolved

                    ' if the editor supports selectable text
                    If editor.SupportsSelectableText Then
                        ' select all the text so it can be replaced
                        editor.SelectionStart = 0
                        editor.SelectionLength = editor.TextLength

                        If TypeOf editor Is EditorWithMask Then
                            ' just clear the selected text and let the grid
                            ' forward the keypress to the editor
                            editor.SelectedText = String.Empty
                        Else
                            ' then replace the selected text with the character
                            editor.SelectedText = New String(e.KeyChar, 1)

                            ' mark the event as handled so the grid doesn't process it
                            e.Handled = True
                        End If
                    End If
                End If
            End If
        End If
    End Sub

    ''' <summary>
    ''' On Key up
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub grdData_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles grdData.KeyUp
        'if delete button is pressed, then the Investor and Managed Fund's positions need to be reset
        If e.KeyCode = Keys.Delete Then
            If grdData.ActiveCell Is Nothing Then Exit Sub
            Dim lstrActiveColName As String = grdData.ActiveCell.Column.Header.Caption
            If mstEditableDataSourceNameCols.Contains(lstrActiveColName) Then
                CalculateInvAndManagedFundPositions(InvestorPositionSources.OnCellChange, True, grdData.ActiveCell)
                SetSoureDateToBlank(grdData.ActiveRow, lstrActiveColName)
            ElseIf lstrActiveColName.StartsWith(mstrCurrentListingColPrefix) OrElse mstPreviousProjects.Find(Function(p) p.DeliveryListing = lstrActiveColName) IsNot Nothing Then
                CalculateInvAndManagedFundPositions(InvestorPositionSources.OnCellChange, False, grdData.ActiveCell)
            End If
        End If
    End Sub

    Private Sub SetSoureDateToBlank(ByRef lugrTraversingRow As UltraGridRow, ByVal lstrActiveColName As String)
        If lugrTraversingRow.GetCellValue(lstrActiveColName).ToString.Equals("") AndAlso mstAllDataSourceDateCols.Contains(lstrActiveColName + mstrSourceDateColSuffix) Then
            If lugrTraversingRow.Cells(lstrActiveColName + mstrSourceDateColSuffix).Value.ToString.Equals("") = False Then
                lugrTraversingRow.Cells(lstrActiveColName + mstrSourceDateColSuffix).Value = DBNull.Value
            End If
        End If
        If lugrTraversingRow.GetCellValue(lstrActiveColName).ToString.Equals("") AndAlso mstResearchSourceCols.Contains(lstrActiveColName + mstrSourceColSuffix) Then
            If lugrTraversingRow.Cells(lstrActiveColName + mstrSourceColSuffix).Value.ToString.Equals("") = False Then
                lugrTraversingRow.Cells(lstrActiveColName + mstrSourceColSuffix).Value = ""
            End If
        End If
    End Sub

    ''' <summary>
    ''' To show the right click menus
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub grdData_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles grdData.MouseUp
        Dim mousePoint As Point = Nothing
        Try
            mousePoint = New Point(e.X, e.Y)
            If e.Button = Windows.Forms.MouseButtons.Left Then
                Dim el As UIElement = grdData.DisplayLayout.UIElement.ElementFromPoint(mousePoint)
                If el Is Nothing Then Exit Sub
                Dim lColHeader As ColumnHeader
                lColHeader = el.GetContext(GetType(Infragistics.Win.UltraWinGrid.ColumnHeader))
                If lColHeader IsNot Nothing Then
                    grdData.DisplayLayout.Override.SelectTypeCell = Infragistics.Win.UltraWinGrid.SelectType.Default
                    grdData.DisplayLayout.Override.SelectTypeCol = Infragistics.Win.UltraWinGrid.SelectType.Default
                    grdData.DisplayLayout.Override.SelectTypeRow = SelectType.Default
                Else
                    grdData.DisplayLayout.Override.SelectTypeCell = Infragistics.Win.UltraWinGrid.SelectType.ExtendedAutoDrag
                    grdData.DisplayLayout.Override.SelectTypeCol = Infragistics.Win.UltraWinGrid.SelectType.Single
                    grdData.DisplayLayout.Override.SelectTypeRow = SelectType.Extended
                End If
            ElseIf e.Button = Windows.Forms.MouseButtons.Right Then
                ShowContextMenu(mousePoint)
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            mousePoint = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' If there is any error in the grid because of MultiCellOperations, ignore it
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub grdData_Error(ByVal sender As Object, ByVal e As Infragistics.Win.UltraWinGrid.ErrorEventArgs) Handles grdData.Error
        If e.MultiCellOperationErrorInfo IsNot Nothing Then
            e.Cancel = True
        End If
    End Sub

    ''' <summary>
    ''' Hanles the Multiecelloperation
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub grdData_BeforeMultiCellOperation(ByVal sender As Object, ByVal e As Infragistics.Win.UltraWinGrid.BeforeMultiCellOperationEventArgs) Handles grdData.BeforeMultiCellOperation
        Try
            'Handles the Cut operation manually
            If e.Operation = MultiCellOperation.Cut Then
                e.Cancel = True
                PerformCutOperation()
            ElseIf e.Operation = MultiCellOperation.Paste Then
                'Handles the Paste operation manually
                e.Cancel = True
                PerformInsertOperation()
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, 0)
        End Try
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub PasteCopiedData(ByVal pstrCopiedData As String, ByVal pstrPasteData As String)
        Try
            grdData.BeginUpdate()
            grdData.SuspendRowSynchronization()
            grdData.EventManager.SetEnabled(Infragistics.Win.UltraWinGrid.GridEventIds.AfterCellUpdate, False)
            For Each row As UltraGridRow In grdData.Rows
                row.Cells(pstrPasteData).Value = row.GetCellValue(pstrCopiedData)
            Next
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, 0)
        Finally
            grdData.EventManager.SetEnabled(Infragistics.Win.UltraWinGrid.GridEventIds.AfterCellUpdate, True)
            grdData.EndUpdate()
            grdData.Update()
            grdData.ResumeRowSynchronization()
        End Try
    End Sub

    Private Sub PasteInCurrentColumn(ByVal strColumnName As String)
        'Dim ldtGridData As DataTable
        Try
            grdData.BeginUpdate()
            grdData.SuspendRowSynchronization()
            grdData.EventManager.SetEnabled(Infragistics.Win.UltraWinGrid.GridEventIds.AfterCellUpdate, False)
            If grdData.ActiveCell IsNot Nothing Then
                grdData.ActiveCell.Value = grdData.Rows(grdData.ActiveCell.Row.Index).Cells(strColumnName).Value
            End If
            If grdData.Selected.Cells.Count > 0 Then
                For Each cell As UltraGridCell In grdData.Selected.Cells
                    cell.Value = grdData.Rows(cell.Row.Index).Cells(strColumnName).Value
                Next
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, 0)
        Finally
            grdData.EventManager.SetEnabled(Infragistics.Win.UltraWinGrid.GridEventIds.AfterCellUpdate, True)
            grdData.EndUpdate()
            grdData.Update()
            grdData.ResumeRowSynchronization()
        End Try
    End Sub

#End Region

#Region "Text Box Events"

    ''' <summary>
    ''' Set default DE Notes text
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub txtDENotes_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDENotes.GotFocus
        SetDENotesText(txtDENotes)
    End Sub

    ''' <summary>
    ''' Set default FL Notes text
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub txtFLNotes_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtFLNotes.GotFocus
        SetDENotesText(txtFLNotes)
    End Sub

    ''' <summary>
    ''' Save DE Notes on lost focus
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub txtDENotes_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDENotes.LostFocus
        SaveNotes(True)
    End Sub

    ''' <summary>
    ''' Save FL Notes on lost focus
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub txtFLNotes_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtFLNotes.LostFocus
        SaveNotes(False)
    End Sub

    ''' <summary>
    ''' To set the text
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub txtInvestor_GotFocus(ByVal sender As System.Object, ByVal e As EventArgs) Handles txtInvestor.GotFocus '
        'Once the focus is on Investor text box and it has the default text in it, then set it to empty
        If MessageManager.GetMessage("DEFAULTSEARCHTEXT") = txtInvestor.Text Then
            txtInvestor.Text = String.Empty
        End If
    End Sub

    ''' <summary>
    ''' To set the text while leaving it
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub txtInvestor_Leave(ByVal sender As Object, ByVal e As EventArgs) Handles txtInvestor.Leave
        'If it's empty, set it to the default text
        If String.IsNullOrEmpty(txtInvestor.Text.Trim()) Then
            SetDefaulSearchText(txtInvestor)
        End If
    End Sub

    ''' <summary>
    ''' To set the text
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub txtFund_GotFocus(ByVal sender As System.Object, ByVal e As EventArgs) Handles txtFund.GotFocus
        If MessageManager.GetMessage("DEFAULTSEARCHTEXT") = txtFund.Text Then
            txtFund.Text = String.Empty
        End If
    End Sub

    ''' <summary>
    ''' To set the text while leaving it
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub txtFund_Leave(ByVal sender As Object, ByVal e As EventArgs) Handles txtFund.Leave
        If String.IsNullOrEmpty(txtFund.Text.Trim()) Then
            SetDefaulSearchText(txtFund)
        End If
    End Sub

#End Region

#Region "Button Events"
    ''' <summary>
    ''' Save the data hub changes in the database
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        SaveData(True, True)
    End Sub

    ''' <summary>
    ''' To find the records whose Investor's row's value does not match with the sum of funds
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnCheckForSumup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheckForSumup.Click
        Dim lintInvestorRowIndex As Integer = 0
        Dim lblnIsSumOfFunds As Boolean = True
        Dim lstLockedCols As List(Of CurrentDataSources) = Nothing
        Dim lblnIsSumError As Boolean = False
        Dim lintInvestorPositions As Int64 = 0
        Dim rootband As UltraGridBand = grdData.Rows.Band
        Dim lugrTraversingRow As UltraGridRow = Nothing
        Dim lstColumnsToBeChecked As New List(Of String)
        Try
            'If No column is locked, then inform the user
            If menmScreenType = DataHubScreenType.DataEntry Then
                lstLockedCols = mstCurrentDataSources.FindAll(Function(p) p.AccessStatus = SourceAccessbility.Locked.ToString)
                If lstLockedCols.Count = 0 Then
                    MessageBox.Show("Please lock a column first before searching for sum of funds error.", CommonCLL.mstrMsgBoxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Exit Sub
                End If
                For Each lobjLockedDataSource As CurrentDataSources In lstLockedCols
                    lstColumnsToBeChecked.Add(lobjLockedDataSource.SourceName)
                Next
            Else
                'Get the columns to be checked from the column list form
                lstColumnsToBeChecked = CallColumnList(True)
            End If
            If lstColumnsToBeChecked Is Nothing Then Exit Sub
            If lstColumnsToBeChecked.Count = 0 Then Exit Sub

            CancelOutCutOperation()
            'Clear the old filters
            rootband.ColumnFilters.ClearAllFilters()
            rootband.ColumnFilters("InvestorName").FilterConditions.Add(FilterComparisionOperator.Equals, "")

            'Traverse the grid and find the investors whose position value is less than Sum of it's associated Non-Managed Funds
            While lintInvestorRowIndex < grdData.Rows.Count
                lblnIsSumError = False
                'If it's coming for second time onwards, then find the index of investor row
                If lintInvestorRowIndex <> 0 Then
                    lintInvestorRowIndex = FindNextInvestorIndex(lintInvestorRowIndex + 1)
                    'If the index suceeds the row count, then exit
                    If lintInvestorRowIndex >= grdData.Rows.Count OrElse lintInvestorRowIndex = 0 Then Exit While
                End If
                lugrTraversingRow = grdData.Rows(lintInvestorRowIndex)
                'Compare the sum of funds for all locked columns
                If lstColumnsToBeChecked Is Nothing Then Exit Sub
                ' If grdData.ActiveCell Is Nothing Then Exit Sub

                For Each lstrColName As String In lstColumnsToBeChecked
                    'See if the SumOfFunds status if True
                    lblnIsSumOfFunds = CheckSumOfFunds(grdData.Rows(lintInvestorRowIndex).GetCellValue("InvestorID"), lstrColName, False, False)
                    'lblnIsSumOfFunds = CheckSumOfFunds(lintInvestorRowIndex, grdData.ActiveCell.Column.Header.Caption)
                    'If it's Manual, then calculate the positions of Non-Managed Funds
                    If lblnIsSumOfFunds = False Then
                        If lugrTraversingRow.GetCellValue(lstrColName).ToString.Equals("") = False AndAlso lugrTraversingRow.GetCellValue(lstrColName).ToString.Equals(mstrNDValue) = False Then
                            lintInvestorPositions = Convert.ToInt64(lugrTraversingRow.GetCellValue(lstrColName))
                        End If
                        If lintInvestorPositions < CalculateSumOfFundPositions(lintInvestorRowIndex, lstrColName, True) Then
                            lblnIsSumError = True
                            Exit For
                        End If
                    End If
                Next
                'If it's a Sum Error, then add it in the filter list
                If lblnIsSumError Then
                    rootband.ColumnFilters("InvestorName").LogicalOperator = FilterLogicalOperator.Or
                    rootband.ColumnFilters("InvestorName").FilterConditions.Add(FilterComparisionOperator.Equals, grdData.Rows(lintInvestorRowIndex).GetCellValue("InvestorName"))
                End If
                If lintInvestorRowIndex = 0 Then
                    lintInvestorRowIndex = 1
                End If
            End While
            'Refresh the filters which will result just to show the funds rows; but we need the associated investor rows too, see the code below for this
            grdData.DisplayLayout.RefreshFilters()

            menmSearchResultType = SearchResultType.CustomSearch
            SetSearchFilterResultText(menmSearchResultType)
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            rootband = Nothing
            lugrTraversingRow = Nothing
            lstLockedCols = Nothing
            lstColumnsToBeChecked = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' To collapse or expand the panel
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnCollapse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCollapse.Click
        If spcDataHub.Panel2Collapsed Then
            spcDataHub.Panel2Collapsed = False
        Else
            spcDataHub.Panel2Collapsed = True
        End If
    End Sub

    ''' <summary>
    ''' Display the Merge and Acquired 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnMAs_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnMAs.Click
        Dim lfrmMergersAndAcquisitions As New MergersAndAcquisitions
        Try
            'If instance already exist than bring to front.
            If Not CommonCLL.FocusOnExistingInstanceByName("MergersAndAcquisitions") Then
                Application.OpenForms("MergersAndAcquisitions").WindowState = FormWindowState.Maximized
                Application.OpenForms("MergersAndAcquisitions").BringToFront()
            Else
                'Start the new instance of Merge and Acquired.
                lfrmMergersAndAcquisitions.mintProjectID = mintProjectID
                lfrmMergersAndAcquisitions.Show()
                lfrmMergersAndAcquisitions.BringToFront()
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, "M & As", mintProjectID)
        Finally
            lfrmMergersAndAcquisitions = Nothing
        End Try

    End Sub

    ''' <summary>
    ''' Displat the toop tip on mouse enter
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnCheckForSumup_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs)
        'Pass the control and message to display the tooltip.
        ShowToolTip(sender, MessageManager.GetMessage(DBResult.DE_TOOLTIP_BTN_CHECKSUM_1.ToString) + _
                                        Environment.NewLine + MessageManager.GetMessage(DBResult.DE_TOOLTIP_BTN_CHECKSUM_2.ToString))
    End Sub

    ''' <summary>
    ''' disable the tooltipmanager when mouse leave the control.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnCheckForSumup_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs)
        UltraToolTipManager1.Enabled = False
    End Sub

    ''' <summary>
    ''' Displat the toop tip on mouse enter
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnColumns_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnColumns.MouseEnter
        'Pass the control and message to display the tooltip.
        ShowToolTip(sender, MessageManager.GetMessage(DBResult.DE_TOOLTIP_BTN_COLUMNS.ToString))
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnColumns_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnColumns.MouseLeave
        UltraToolTipManager1.Enabled = False
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnCancelSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancelSearch.Click
        If mthdThread Is Nothing Then Exit Sub
        If mthdThread.IsAlive Then
            If mthdThread.ThreadState = 68 Then
                mthdThread.Resume()
            End If
            mthdThread.Abort()
            If bgwSqlWorker.IsBusy Then
            End If
            bgwSqlWorker.CancelAsync()
        End If
        mthdThread = Nothing
    End Sub

    ''' <summary>
    ''' Displat the toop tip on mouse enter
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnCancelSearch_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancelSearch.MouseEnter
        'Pass the control and message to display the tooltip.
        ShowToolTip(sender, MessageManager.GetMessage(DBResult.DE_TOOLTIP_BTN_CANCELSEARCH.ToString))
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnCancelSearch_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancelSearch.MouseLeave
        UltraToolTipManager1.Enabled = False
    End Sub

    ''' <summary>
    ''' Displat the toop tip on mouse enter
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnAutoSave_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAutoSave.MouseEnter
        'Pass the control and message to display the tooltip.
        ShowToolTip(sender, MessageManager.GetMessage(DBResult.DE_TOOLTIP_BTN_AUTOSAVE_1.ToString) + _
                                        Environment.NewLine + MessageManager.GetMessage(DBResult.DE_TOOLTIP_BTN_AUTOSAVE_2.ToString))
    End Sub

    ''' <summary>
    ''' To undo
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnUndo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUndo.Click
        grdData.PerformAction(Infragistics.Win.UltraWinGrid.UltraGridAction.Undo)
    End Sub

    ''' <summary>
    ''' To Redo
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnRedo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRedo.Click
        grdData.PerformAction(Infragistics.Win.UltraWinGrid.UltraGridAction.Redo)
    End Sub

    ''' <summary>
    ''' Displat the toop tip on mouse enter
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnExit_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExit.MouseEnter
        'Pass the control to display the tooltip.
        ShowToolTip(sender, MessageManager.GetMessage(DBResult.DE_TOOLTIP_BTN_EXIT.ToString))
    End Sub

    ''' <summary>
    ''' To see the change mapping log 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btneSourceNotes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btneSourceNotes.Click
        Dim lfrmChangeMappingLog As New ChangeMappingLog(mintProjectID)
        lfrmChangeMappingLog.Show()
    End Sub

    ''' <summary>
    ''' To exit the form
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
        Me.Close()
    End Sub

    ''' <summary>
    ''' Hide/Unhide the columns.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnColumns_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnColumns.Click
        CallColumnList(False)
    End Sub

    Private Function CallColumnList(ByVal lblnIsFromSumupError As Boolean) As List(Of String)
        Dim lfrmColumnList As New ColumnList
        Dim lobjCDS As CurrentDataSources = Nothing
        Dim lcdsShortCut As New CurrentDataSources
        Dim lstSumupErrorColumns As List(Of String) = Nothing
        Dim lstVisibleColumnFl As New List(Of String)
        Dim dtGridData As DataTable
        'Dim ldicColumnShortCut As Dictionary(Of String, String)
        'Clear the array.
        Array.Resize(marrAllVisibleSourceNameCols, 1)
        mdtAppendCurrentDataSource = New DataTable
        'Dim dtGridData As DataTable
        Dim lclsCLM As New ColumnListManager
        Try
            ' Throw New Exception("Oh no!")
            'Make an array of all visible columns.
            For Each lCol As UltraGridColumn In grdData.DisplayLayout.Bands(0).Columns
                If lCol.Hidden = False Then
                    If Not marrPreviousDataSourceNameCols.Contains(lCol.Key.ToString) And Not marrPreviousSourceDateCols.Contains(lCol.Key.ToString) Then
                        If marrAllVisibleSourceNameCols.Length = 1 Then
                            marrAllVisibleSourceNameCols(0) = lCol.Key.ToString
                        Else
                            marrAllVisibleSourceNameCols(marrAllVisibleSourceNameCols.Length - 1) = lCol.Key.ToString
                        End If
                        ReDim Preserve marrAllVisibleSourceNameCols(marrAllVisibleSourceNameCols.Length)
                    End If
                End If
                If Not marrPreviousDataSourceNameCols.Contains(lCol.Key.ToString) And Not marrPreviousSourceDateCols.Contains(lCol.Key.ToString) Then
                    If marrAllColumnsDataHub.Length = 1 Then
                        marrAllColumnsDataHub(0) = lCol.Header.Caption.ToString
                    Else
                        marrAllColumnsDataHub(marrAllColumnsDataHub.Length - 1) = lCol.Header.Caption.ToString
                    End If
                    ReDim Preserve marrAllColumnsDataHub(marrAllColumnsDataHub.Length)
                End If
            Next
            ReDim Preserve marrAllVisibleSourceNameCols(marrAllVisibleSourceNameCols.Length - 2)
            ' temp dupin ReDim Preserve marrAllColumnsDataHub(marrAllColumnsDataHub.Length - 2)
            lfrmColumnList.Text = TitleManager.GetTitle("ColumnList")
            lfrmColumnList.mintProjectID = mintProjectID
            lfrmColumnList.marrAllVisibleSourceNameCols = marrAllVisibleSourceNameCols
            lfrmColumnList.mstrAllColumnsDataHub = marrAllColumnsDataHub
            'Set the previous expand collapse status. array contain the string.
            lfrmColumnList.mstrCollapsedCategories = mstrCollapsedCategories
            'Also Attach an event.
            AddHandler lfrmColumnList.CheckNDNILStatus, AddressOf CheckInvalidValue
            lfrmColumnList.mstCurrentDataSourcesDataHub = mstCurrentDataSources
            If menmScreenType = DataHubScreenType.DataEntry Then
                lfrmColumnList.mblnDataHub = True
            Else
                lfrmColumnList.mblnDataHub = False
            End If
            lfrmColumnList.mblnSumUp = lblnIsFromSumupError
            If Not mblnColumnListStatus Then
                GetVisibleColumnsFL(lstVisibleColumnFl)
            End If
            lfrmColumnList.mlstVisibleColumnsFL = lstVisibleColumnFl
            'lfrmColumnList.mblnDataHub = False
            lfrmColumnList.ShowDialog()
            If lfrmColumnList.mblnDataHub Then
                Array.Resize(marrAllVisibleSourceNameCols, 1)
                marrAllVisibleSourceNameCols = lfrmColumnList.marrAllReturnSourceNameCols
                If lfrmColumnList.mlstNewAddedColumns IsNot Nothing Then
                    If lfrmColumnList.mlstNewAddedColumns.Count > 0 Then
                        AddNewColumnsDataHub(lfrmColumnList.mlstNewAddedColumns)
                    End If
                End If
                If marrAllVisibleSourceNameCols Is Nothing Then Return Nothing
                'Set the state of collapse and expand. 
                mstrCollapsedCategories = lfrmColumnList.mstrCollapsedCategories
                'Set the AppendCurrentDataSource. 
                mdtAppendCurrentDataSource = lfrmColumnList.mdtAppendNDNIL
                'Update the column header if ND/NIL is changed.
                If mdtAppendCurrentDataSource IsNot Nothing Then
                    If mdtAppendCurrentDataSource.Rows.Count > 0 Then
                        SetDataSourceColumnListReturn()
                    End If
                End If
                'Hide the columns contain in array.
                DataColumnsHidden(True)
                'To check if a Recall Data change is required, To hide/unhide the columns and to add the new columns for Add New column
                ''Check if new column is added.
            Else
                If lblnIsFromSumupError Then
                    lstSumupErrorColumns = lfrmColumnList.mlstSumUpErrors
                End If
                If lfrmColumnList.mlstNewAddedColumns IsNot Nothing Then
                    If lfrmColumnList.mlstNewAddedColumns.Count > 0 Then
                        'dtGridData = CType(grdData.DataSource, DataTable)
                        AddNewColumnsDataHub(lfrmColumnList.mlstNewAddedColumns)
                    End If
                End If
                mstrCollapsedCategories = lfrmColumnList.mstrCollapsedCategories
                mdtAppendCurrentDataSource = lfrmColumnList.mdtAppendNDNIL
                'Update the column header if ND/NIL is changed.
                If mdtAppendCurrentDataSource IsNot Nothing Then
                    SetDataSourceColumnListReturn()
                End If

                If lfrmColumnList.marrVisibleParentCols(0) IsNot Nothing Then
                    mblnColumnListStatus = True
                    marrVisibleColumnsFL = lfrmColumnList.marrVisibleParentCols
                    AddMissingColumnFL()
                    DataColumnsHidden(False)
                End If
                mstrCollapsedCategories = lfrmColumnList.mstrCollapsedCategories
                Dim lvar As String = String.Empty
                Dim lstrShortcut As String = String.Empty
                If lfrmColumnList.mdicShortCutColumn.Count = 0 Then Return lstSumupErrorColumns
                mdicShortCut = lfrmColumnList.mdicShortCutColumn
                If lfrmColumnList.mdicShortCutColumn IsNot Nothing Then
                    For Each item In lfrmColumnList.mdicShortCutColumn
                        lvar = item.Key
                        lstrShortcut = item.Value
                        If lcdsShortCut Is Nothing Then
                            lcdsShortCut = New CurrentDataSources
                        End If
                        lcdsShortCut = mstCurrentDataSources.Find(Function(p) p.SourceName = lvar) ' = lstCDS.EntityID.ToString)
                        If lcdsShortCut IsNot Nothing Then
                            lcdsShortCut.AlphaShortcut = lstrShortcut
                        End If
                    Next
                End If
                'mblnColumnListStatus = False
                Return lstSumupErrorColumns
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, "ColumnList", mintProjectID)
            Return Nothing
        Finally
            lstSumupErrorColumns = Nothing
            lfrmColumnList = Nothing
            mdtAppendCurrentDataSource = Nothing
            lclsCLM = Nothing
        End Try
    End Function

    ''' <summary>
    ''' Change the default values. Retrive from the db.    
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub SetFLColumnVisibilityStatus()
        Dim lclsColumnListManager As New ColumnListManager
        Dim lstrHiddenColumns As String
        Dim larrStr() As String
        Dim rootband As UltraGridBand = grdData.Rows.Band
        Try
            lstrHiddenColumns = lclsColumnListManager.RetrieveHiddenColumns(mintProjectID)
            larrStr = lstrHiddenColumns.Split("~")
            If lstrHiddenColumns = String.Empty Then
                For Each lobjCurrentSource As CurrentDataSources In mstCurrentDataSources
                    If lobjCurrentSource.SourceTypeCode = SourceTypeCode.RSH.ToString OrElse lobjCurrentSource.SourceTypeCode = SourceTypeCode.PBC.ToString OrElse _
                        lobjCurrentSource.ESourceCode = DataSourceCode.DDALCOT.ToString OrElse lobjCurrentSource.ESourceCode = DataSourceCode.EDDALOT.ToString Then Continue For
                    If rootband.Columns.Exists(lobjCurrentSource.SourceName) Then
                        rootband.Columns(lobjCurrentSource.SourceName).Hidden = True
                    End If
                    If rootband.Columns.Exists(lobjCurrentSource.SourceDate) Then
                        rootband.Columns(lobjCurrentSource.SourceDate).Hidden = True
                    End If
                Next
            Else
                For Each lCol As String In larrStr
                    If rootband.Columns.Exists(lCol.Trim) Then
                        rootband.Columns(lCol.Trim).Hidden = True
                    End If
                Next
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            rootband = Nothing
            lclsColumnListManager = Nothing
            lstrHiddenColumns = Nothing
        End Try
    End Sub

    Private Sub AddMissingColumnFL()
        If marrVisibleColumnsFL IsNot Nothing Then
            For Each StrColumnName As String In marrVisibleColumnsFL
                If StrColumnName IsNot Nothing Then
                    If StrColumnName.Contains(mstrDDAllocationColPrefix) Then
                        If Not grdData.DisplayLayout.Bands(0).Columns.Exists(StrColumnName) Then
                            grdData.DisplayLayout.Bands(0).Columns.Add(StrColumnName)
                        End If
                    End If
                End If
            Next
        End If
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="mstCurrentDataSources"></param>
    ''' <remarks></remarks>
    Private Sub AddNewColumnsDataHub(ByVal mlstCurrentDataSources As List(Of CurrentDataSources))
        Dim dtGridData As DataTable
        Dim lclsCLM As New ColumnListManager
        Dim lintLockedColCount As Integer
        Dim lstSourceName As New List(Of String)
        Dim lstSourceDate As New List(Of String)
        Dim strColumnName As String = String.Empty
        Dim lstObj As CurrentDataSources
        dtGridData = CType(grdData.DataSource, DataTable)
        For Each lstCurrentDataSource As CurrentDataSources In mlstCurrentDataSources
            strColumnName = lstCurrentDataSource.SourceName.ToString
            If Not strColumnName.Equals(String.Empty) Then
                lstObj = mstCurrentDataSources.Find(Function(p) p.SourceName = strColumnName)
                If lstObj IsNot Nothing Then Continue For
                lstCurrentDataSource.EntityID = lclsCLM.GetEntityID(strColumnName.ToString)
                dtGridData.Columns.Add(lstCurrentDataSource.SourceName)
                If menmScreenType = DataHubScreenType.DataEntry Then
                    lintLockedColCount = GetOrdinal()
                    lintLockedColCount = lintLockedColCount + 1
                    'grdData.DisplayLayout.Bands(0).Columns.Add(strColumnName)
                    grdData.Rows.Band.Columns(lstCurrentDataSource.SourceName).Header.VisiblePosition = lintLockedColCount
                Else
                    lintLockedColCount = CheckDataSource(lstCurrentDataSource)
                    lintLockedColCount = lintLockedColCount + 1
                    'grdData.DisplayLayout.Bands(0).Columns.Add(strColumnName)
                    grdData.Rows.Band.Columns(strColumnName).Header.VisiblePosition = lintLockedColCount
                End If
                grdData.Rows.Band.Columns(strColumnName).CellActivation = Activation.NoEdit
                If lstCurrentDataSource.IsND Or lstCurrentDataSource.IsNIL Then
                    SetAppereanceHeader(strColumnName)
                End If
                lstSourceName.Add(strColumnName)
                If lstCurrentDataSource.SourceDate IsNot Nothing Then
                    If marrDateSuppertedSourceTypes.Contains(lstCurrentDataSource.ESourceCode) Then
                        dtGridData.Columns.Add(lstCurrentDataSource.SourceDate, GetType(Date))
                        grdData.Rows.Band.Columns(lstCurrentDataSource.SourceDate).Header.VisiblePosition = lintLockedColCount + 1
                        lstSourceDate.Add(lstCurrentDataSource.SourceDate)
                        grdData.Rows.Band.Columns(lstCurrentDataSource.SourceDate).CellActivation = Activation.NoEdit
                    End If
                    'grdData.DisplayLayout.Bands(0).Columns.Add(lstCurrentDataSource.SourceDate)
                End If
                mstCurrentDataSources.Add(lstCurrentDataSource)
            End If
        Next
        If Not lstSourceName.Equals(String.Empty) Then
            UpdateColumnRelatedData(lstSourceName, lstSourceDate, False)
        End If
        FocusOnAddedColumn(mlstCurrentDataSources(mlstCurrentDataSources.Count - 1).SourceName.ToString)
        dtGridData.AcceptChanges()
    End Sub

    ''' <summary>
    ''' Update the DataSource of DataHub.
    ''' </summary>
    ''' <param name="strSourceData"></param>
    ''' <param name="strDateData"></param>
    ''' <param name="lblnDelete"></param>
    ''' <remarks></remarks>
    Private Sub UpdateColumnRelatedData(ByVal strSourceData As List(Of String), ByVal strDateData As List(Of String), ByVal lblnDelete As Boolean)
        Dim lstr = String.Empty
        If lblnDelete Then
            For Each lstrEntity As String In strSourceData
                If lstr = String.Empty Then
                    lstr = lstrEntity
                Else
                    lstr = lstr + "," + lstrEntity
                End If
            Next
            DeleteDataEntityFromFrontEnd(lstr, grdData.DataSource)
        Else
            For Each lstrData As String In strSourceData
                If Not mstAllDataSourceNameCols.Contains(lstrData) Then
                    mstAllDataSourceNameCols.Add(lstrData)
                End If
                If Not mstEditableDataSourceNameCols.Contains(lstrData) Then
                    mstEditableDataSourceNameCols.Add(lstrData)
                End If
            Next
            For Each lstrDate As String In strDateData
                If Not mstAllDataSourceDateCols.Contains(lstrDate) Then
                    mstAllDataSourceDateCols.Add(lstrDate)
                End If
            Next
        End If
    End Sub
    'Private Sub UpdateColumnRelatedData(ByVal lstCurrentDataSource As CurrentDataSources)
    '    mstCurrentDataSources.Add(lstCurrentDataSource)
    '    mstAllDataSourceNameCols.Add(lstCurrentDataSource.SourceName)
    '    mstEditableDataSourceNameCols.Add(lstCurrentDataSource.SourceName)
    '    If marrDateSuppertedSourceTypes.Contains(lstCurrentDataSource.ESourceCode) Then
    '        mstAllDataSourceDateCols.Add(lstCurrentDataSource.SourceDate)
    '    End If
    'End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function GetOrdinal() As Integer
        Dim lintLockedColCount As Integer = mstCurrentDataSources.FindAll(Function(p) p.AccessStatus = SourceAccessbility.Locked.ToString).Count
        lintLockedColCount = lintLockedColCount + mintParentIndex
        Return lintLockedColCount
    End Function


    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="lstCurrentDataSource"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function CheckDataSource(ByVal lstCurrentDataSource As CurrentDataSources) As Integer
        Dim dtGridData As DataTable
        Dim visibleIndex As Integer = 0
        Dim lstrColumnName As String = String.Empty
        'Get the DataSourceName Parent of EntityId Column.
        If lstCurrentDataSource.SourceTypeCode = SourceTypeCode.UPD.ToString Then
            lstrColumnName = mstrUpdatesColPrefix + lstCurrentDataSource.ListingName.ToString
        ElseIf lstCurrentDataSource.SourceTypeCode = SourceTypeCode.RGT.ToString Or lstCurrentDataSource.SourceTypeCode = SourceTypeCode.REG.ToString Then
            lstrColumnName = mstrRegisterColPrefix + lstCurrentDataSource.ListingName.ToString
        ElseIf lstCurrentDataSource.SourceTypeCode = SourceTypeCode.BKL.ToString Or lstCurrentDataSource.SourceTypeCode = SourceTypeCode.EBL.ToString _
            Or lstCurrentDataSource.SourceTypeCode = SourceTypeCode.PRB.ToString Or lstCurrentDataSource.SourceTypeCode = SourceTypeCode.EPB.ToString Then
            lstrColumnName = mstrBanklistColPrefix + lstCurrentDataSource.ListingName.ToString
        ElseIf lstCurrentDataSource.SourceTypeCode = SourceTypeCode.DDI.ToString Then
            If lstCurrentDataSource.ESourceID <> DataSourceCode.DDALCOT Then
                lstrColumnName = mstrDDInfoColPrefix + lstCurrentDataSource.ListingName.ToString
            End If
        End If
        If lstrColumnName.Equals(String.Empty) Then
            If grdData.Rows.Band.Columns.Exists(mstrCurrentListingColPrefix + lstCurrentDataSource.ListingName.ToString) Then
                Return grdData.Rows.Band.Columns(mstrCurrentListingColPrefix + lstCurrentDataSource.ListingName.ToString).Header.VisiblePosition
            End If
        End If
        'If Exists and get the visiblepostion.
        If grdData.Rows.Band.Columns.Exists(lstrColumnName) Then
            visibleIndex = grdData.Rows.Band.Columns(lstrColumnName).Header.VisiblePosition
            grdData.Rows.Band.Columns(lstrColumnName).Hidden = False

            If grdData.Rows.Band.Columns.Exists(lstrColumnName + mstrSourceDateColSuffix) Then
                visibleIndex = grdData.Rows.Band.Columns(lstrColumnName + mstrSourceDateColSuffix).Header.VisiblePosition
                grdData.Rows.Band.Columns(lstrColumnName + mstrSourceDateColSuffix).Hidden = False
            End If

            If grdData.Rows.Band.Columns.Exists(lstrColumnName + mstrSourceColSuffix) Then
                visibleIndex = grdData.Rows.Band.Columns(lstrColumnName + mstrSourceColSuffix).Header.VisiblePosition
                grdData.Rows.Band.Columns(lstrColumnName + mstrSourceColSuffix).Hidden = False
            End If
            'Else add to grid and DataTable also.
        Else
            If grdData.Rows.Band.Columns.Exists(mstrCurrentListingColPrefix + lstCurrentDataSource.ListingName.ToString) Then
                visibleIndex = grdData.Rows.Band.Columns(mstrCurrentListingColPrefix + lstCurrentDataSource.ListingName.ToString).Header.VisiblePosition
                dtGridData = CType(grdData.DataSource, DataTable)
                If lstCurrentDataSource.SourceTypeCode = SourceTypeCode.DDI.ToString Or lstCurrentDataSource.SourceTypeCode = SourceTypeCode.UPD.ToString Then
                    If lstCurrentDataSource.ESourceCode <> DataSourceCode.DDALCOT.ToString Then
                        dtGridData.Columns.Add(lstrColumnName)
                        dtGridData.Columns.Add(lstrColumnName + mstrSourceDateColSuffix)
                        If grdData.DisplayLayout.Bands(0).Columns.Contains(lstrColumnName) Then
                            visibleIndex = visibleIndex + 1
                            grdData.Rows.Band.Columns(lstrColumnName).Header.VisiblePosition = visibleIndex
                        Else
                            grdData.Rows.Band.Columns.Add(lstrColumnName)
                            visibleIndex = visibleIndex + 1
                            grdData.Rows.Band.Columns(lstrColumnName).Header.VisiblePosition = visibleIndex
                        End If
                        If Not grdData.Rows.Band.Columns.Contains(lstrColumnName + mstrSourceDateColSuffix) Then
                            visibleIndex = visibleIndex + 1
                            grdData.Rows.Band.Columns.Add(lstrColumnName + mstrSourceDateColSuffix)
                            grdData.Rows.Band.Columns(lstrColumnName + mstrSourceDateColSuffix).Header.VisiblePosition = visibleIndex
                        Else
                            visibleIndex = visibleIndex + 1
                            grdData.Rows.Band.Columns(lstrColumnName + mstrSourceDateColSuffix).Header.VisiblePosition = visibleIndex
                        End If
                        If Not mstDataSourceParentGroupPositionCol.Contains(lstrColumnName) Then
                            mstDataSourceParentGroupPositionCol.Add(lstrColumnName)
                        End If
                        If Not mstDataSourceParentGroupDateCol.Contains(lstrColumnName + mstrSourceDateColSuffix) Then
                            mstDataSourceParentGroupDateCol.Add(lstrColumnName + mstrSourceDateColSuffix)
                        End If
                    End If
                Else
                    dtGridData.Columns.Add(lstrColumnName)
                    mstDataSourceParentGroupPositionCol.Add(lstrColumnName)
                    grdData.Rows.Band.Columns(lstrColumnName).Header.VisiblePosition = visibleIndex + 1
                End If
            End If
        End If
        Return visibleIndex
    End Function

    ''' <summary>
    ''' Set the back color of column header ND/NIL.
    ''' </summary>
    ''' <param name="strcolumnName"></param>
    ''' <remarks></remarks>
    Private Sub SetAppereanceHeader(ByVal strcolumnName As String)
        If Not grdData.DisplayLayout.Appearances.Exists("NDNILHeaderColor") Then
            grdData.Rows.Band.Columns(strcolumnName).Header.Appearance.BackColor = Color.Red
        Else
            grdData.Rows.Band.Columns(strcolumnName).Header.Appearance.BackColor = grdData.DisplayLayout.Appearances("NDNILHeaderColor").BackColor
        End If
    End Sub
    ''' <summary>
    ''' To sort the grid in Ascending order
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub SortAscending_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSortAscending.Click
        If menmSortingOn = SortingOn.Ascending Then Exit Sub
        menmSortingOn = SortingOn.Ascending
        ConductSorting("")
    End Sub

    ''' <summary>
    ''' To sort the grid in Descending order of Positions
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnSortPosition_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSortPosition.Click
        Dim ldrPreviousDeliveryListings As DataRow = Nothing
        Dim lfrmPreviousPositionSorting As PreviousPositionSorting = Nothing
        Try
            If mstPreviousProjects.Count = 0 Then Exit Sub
            'On load up for the first time ever for the project, the DenseRank and FundDenseRank are 0, hence If they are 0 then DB needs to be hit to get the appropriate values
            'of DenseRank and FundDenseRank. That's mblnAnyChangesInLastProject = 0
            If grdData.Rows(0).GetCellValue("DenseRank") = 0 Then
                mblnAnyChangesInLastProject = True
            End If
            'If menmSortingOn = SortingOn.Positions AndAlso mblnAnyChangesInLastProject = False Then Exit Sub
            'Check the number of previous projects, if there is only one then sort the grid according to that project
            If mstPreviousProjects.Count = 1 Then
                'Set the sort order
                menmSortingOn = SortingOn.Positions
                ConductSorting(mstPreviousProjects.Item(0).DeliveryListing)
            Else
                'Otherwise show the list of the previous projects to the user and let him select a previous project to sort
                lfrmPreviousPositionSorting = New PreviousPositionSorting
                mstPreviousProjects.Reverse()
                lfrmPreviousPositionSorting.mstPreviousProjects = mstPreviousProjects
                'lfrmPreviousPositionSorting.mdtPreviousDeliveryListings.Columns.Add("DeliveryListing", GetType(String))
                'For Each lobjPreviousProjects As PreviousProjects In mstPreviousProjects
                '    ldrPreviousDeliveryListings = lfrmPreviousPositionSorting.mdtPreviousDeliveryListings.NewRow
                '    ldrPreviousDeliveryListings.Item("DeliveryListing") = lobjPreviousProjects.DeliveryListing
                '    lfrmPreviousPositionSorting.mdtPreviousDeliveryListings.Rows.Add(ldrPreviousDeliveryListings)
                'Next
                lfrmPreviousPositionSorting.ShowDialog()
                'Get the selected project's name and sort it accordingly
                If lfrmPreviousPositionSorting.mstrSelectedDeliveryListing.Equals("") = False Then
                    'Set the sort order
                    menmSortingOn = SortingOn.Positions
                    ConductSorting(lfrmPreviousPositionSorting.mstrSelectedDeliveryListing)
                    mstrDeliveryListingToSort = lfrmPreviousPositionSorting.mstrSelectedDeliveryListing
                End If
                mstPreviousProjects.Reverse()
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            lfrmPreviousPositionSorting = Nothing
            ldrPreviousDeliveryListings = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnLoadFromDB_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoadFromDB.Click
        If MessageBox.Show("Do you wish to load the data from DB?", CommonCLL.mstrMsgBoxCaption, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
            SaveData(True, False)
            mstCurrentDataSources = New List(Of CurrentDataSources)
            mstPreviousDataSources = New List(Of PreviousDataSources)
            mstPreviousProjects = New List(Of PreviousProjects)
            grdData.DataSource = Nothing
            LoadGridData(DELoadUpType.CallDatabase)
            grdData.UpdateData()
        End If
    End Sub

    Private Sub btnReview_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReview.Click
        'Dim lfrmReview As New Review
        'Try
        '    'If instance already exist than bring to front.
        '    If menmScreenType = DataHubScreenType.FinalizeList Then
        '        If Not CommonCLL.FocusOnExistingInstanceByName("Review") Then
        '            Application.OpenForms("Review").WindowState = FormWindowState.Maximized
        '            Application.OpenForms("Review").BringToFront()
        '        Else
        '            'Start the new instance of Merge and Acquired.
        '            lfrmReview.mintProjectID = mintProjectID
        '            lfrmReview.mintUserID = CommonCLL.UserID
        '            lfrmReview.Show()
        '            lfrmReview.BringToFront()
        '        End If
        '    End If
        'Catch ex As Exception
        '    Me.FormulateAndLogError(ex, "Review", mintProjectID)
        'Finally
        '    lfrmReview = Nothing
        'End Try
    End Sub

#End Region

#Region "Radio Button Events"

    ''' <summary>
    ''' To untick Master DB checkbox when All is selected
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub rdAll_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rdAll.CheckedChanged
        If rdAll.Checked Then
            chkSearchMasterDB.Checked = False
        End If
    End Sub

    ''' <summary>
    ''' To show all the Project DB Records
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub rdAll_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles rdAll.MouseClick
        'Clear all the filters
        grdData.Rows.Band.ColumnFilters.ClearAllFilters()
        'To show the Investor Name column for Column Filters
        ShowInvestorNameColForColumnFilter()
        'Set the radio buttons and search result type
        menmSearchResultType = SearchResultType.All
        SetSearchFilterResultText(SearchResultType.All)
        'Set the default search text
        SetDefaulSearchText(txtInvestor)
        SetDefaulSearchText(txtFund)
        'Change the grid's rows backcolor to normal, if there are any non-project db rows from the previous search
        ChangeRowColorBackToNormal(grdData.DataSource)
    End Sub

    ''' <summary>
    ''' Set the regular search radio button
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub rdbRegularSearch_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rdbRegularSearch.CheckedChanged
        'If regular search is going to be conducted, then disable the Master DB checkbox
        If rdbRegularSearch.Checked Then
            chkSearchMasterDB.Enabled = False
        End If
    End Sub

    ''' <summary>
    ''' Set the custom search radio button
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub rdbCustomSearch_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rdbCustomSearch.CheckedChanged
        'If custom search is going to be conducted, then enable the Master DB checkbox
        If rdbCustomSearch.Enabled Then
            chkSearchMasterDB.Enabled = True
        End If
    End Sub

    ''' <summary>
    ''' To restrict acess to DE Notes text box
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub rdbDECurrentNotes_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rdbDECurrentNotes.CheckedChanged
        If rdbDECurrentNotes.Checked Then
            txtDENotes.Enabled = True
        Else
            txtDENotes.Enabled = False
        End If
        LoadNotes()
    End Sub

    ''' <summary>
    ''' To restrict acess to FL Notes text box
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub rdbFLCurrentNotes_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rdbFLCurrentNotes.CheckedChanged
        If rdbFLCurrentNotes.Checked Then
            txtFLNotes.Enabled = True
        Else
            txtFLNotes.Enabled = False
        End If
        LoadNotes()
    End Sub

#End Region

#Region "Menu Items"
    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuChangedFund_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuChangedFund.Click
        'Cancel out the cut operations
        CancelOutCutOperation()
        Dim lFundManagement As FundManagement
        Dim ldtGridData As DataTable
        Dim lintFundID As Integer
        Dim lintLinkid As Integer
        Dim lintInvestorID As Integer
        Dim lstrIntendSpace As String = "     "
        Dim lgrow As UltraGridRow
        Dim lblnSaveData As Boolean = True
        Dim lintOldLinkID As Integer
        Try
            'Get the FundId, LinkId, InestorId 
            If grdData.ActiveRow IsNot Nothing Then
                If grdData.ActiveRow.GetCellValue("IsMasterDB") IsNot Nothing Then
                    If grdData.ActiveRow.GetCellValue("IsMasterDB").ToString <> String.Empty Then
                        If grdData.ActiveRow.GetCellValue("IsMasterDB") = True Then
                            Me.ShowMessageBox(DBResult.DE_FUND_MASTERDB)
                            Exit Sub
                        End If
                    End If
                End If
                lintFundID = grdData.ActiveRow.GetCellValue("FundID")
                If lintFundID = 0 Or lintFundID.ToString = String.Empty Then Exit Sub
                lintLinkid = grdData.ActiveRow.GetCellValue("LinkID")
                lintInvestorID = grdData.ActiveRow.GetCellValue("InvestorID")
                'lintInvestorID = GetInvestorID(grdData.ActiveRow.Index)
                If (mclsDataHubManager.CheckRecordExistence("fund", lintFundID) = False) Then
                    MessageBox.Show(MessageManager.GetMessage("RECORD_DELETED/MODIFIED").ToString, m_strMsgBoxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Exit Sub
                End If
                If (mclsDataHubManager.CheckRecordExistence("investor", lintInvestorID) = False) Then
                    MessageBox.Show(MessageManager.GetMessage("RECORD_DELETED/MODIFIED").ToString, m_strMsgBoxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Exit Sub
                End If
            End If
            ldtGridData = New DataTable
            'Pass the FundId,LinkId,InestorId and Open the form to search the new fund.
            lFundManagement = New FundManagement
            lFundManagement.mintProjectID = mintProjectID
            lFundManagement.mintInvestorID = lintInvestorID
            lFundManagement.mintLinkID = lintLinkid
            'Show the form to search the fund.
            lFundManagement.ShowDialog()
            If lFundManagement.mdicFundDetails IsNot Nothing Then
                'Update the selected row fields.
                lgrow = grdData.ActiveRow
                lintOldLinkID = lgrow.GetCellValue("LinkID")
                If grdData.ActiveRow IsNot Nothing Then
                    grdData.ActiveRow.Cells("FundID").Value = lFundManagement.mdicFundDetails("FundID")
                    grdData.ActiveRow.Cells("LinkID").Value = lFundManagement.mdicFundDetails("LinkID")
                    grdData.ActiveRow.Cells("Name").Value = lstrIntendSpace + lFundManagement.mdicFundDetails("FundName").ToString
                    grdData.ActiveRow.Cells("FundName").Value = lFundManagement.mdicFundDetails("FundName")
                    grdData.ActiveRow.Cells("Type").Value = lFundManagement.mdicFundDetails("FundType")
                    grdData.ActiveRow.Cells("Style").Value = lFundManagement.mdicFundDetails("Style")
                    grdData.ActiveRow.Cells("Turnover").Value = lFundManagement.mdicFundDetails("Turnover")
                    grdData.ActiveRow.Cells("Country").Value = lFundManagement.mdicFundDetails("Country")
                    grdData.ActiveRow.Cells("Id").Value = lFundManagement.mdicFundDetails("FndEntityID")
                    grdData.ActiveRow.Cells("Origin").Value = lFundManagement.mdicFundDetails("Origin")
                    grdData.ActiveRow.Cells("InvStatusCode").Value = lFundManagement.mdicFundDetails("InvStatusCode")
                    grdData.ActiveRow.Cells("Region").Value = lFundManagement.mdicFundDetails("Region")
                    grdData.ActiveRow.Cells("Status").Value = lFundManagement.mdicFundDetails("Status")
                End If
                UpdateChangeTrackingTablesForChangeFund(lintOldLinkID, lintInvestorID, lFundManagement.mdicFundDetails("LinkID"), lFundManagement.mdicFundDetails("FundID"))
                AddFlagChangeFund(lintOldLinkID, lFundManagement.mdicFundDetails("LinkID"), lintInvestorID)
                SaveData(lblnSaveData, False)
                grdData.Update()
                grdData.UpdateData()
                'Sort after added or updating the grid data.
                If menmSortingOn = SortingOn.Ascending Then
                    ConductSorting("")
                End If
            End If
            grdData.Update()
            grdData.UpdateData()
            'Sort after added or updating the grid data.
            If menmSortingOn = SortingOn.Ascending Then
                ConductSorting("")
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            lintFundID = Nothing
            lintInvestorID = Nothing
            lintLinkid = Nothing
            lFundManagement = Nothing
            ldtGridData = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="index"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function GetInvestorID(ByVal index As Integer) As Integer
        For i As Integer = index To 0 Step -1
            If grdData.Rows(i).GetCellValue("LinkID") = 0 Then
                Return grdData.Rows(i).GetCellValue("InvestorID")
            End If
        Next
        Return 0
    End Function

    ''' <summary>
    ''' To allow edit a row
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuRowEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuRowEdit.Click
        'Cancel out the cut operations
        CancelOutCutOperation()
        Dim lFundEditForm As AddEditFund
        Dim lInvEditForm As frmAddModifyInvestor
        Dim lintFundID As Integer
        Dim lintLinkid As Integer
        Dim lintInvestorID As Integer
        Dim lstrIntendSpace As String = "     "
        Try
            If grdData.ActiveRow IsNot Nothing Then
                If grdData.ActiveRow.GetCellValue("IsMasterDB").ToString <> String.Empty Then
                    If grdData.ActiveRow.GetCellValue("IsMasterDB") = True Then
                        MessageBox.Show(MessageManager.GetMessage("DE_FUND_MASTERDB").ToString, m_strMsgBoxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information)
                        Exit Sub
                    End If
                End If
                lintFundID = grdData.ActiveRow.GetCellValue("FundID")
                lintLinkid = grdData.ActiveRow.GetCellValue("LinkID")
                lintInvestorID = grdData.ActiveRow.GetCellValue("InvestorID")

                If lintLinkid = 0 Then
                    If (mclsDataHubManager.CheckRecordExistence("investor", lintInvestorID) = False) Then
                        MessageBox.Show(MessageManager.GetMessage("RECORD_DELETED/MODIFIED").ToString, m_strMsgBoxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information)
                        Exit Sub
                    End If
                    lInvEditForm = New frmAddModifyInvestor
                    lInvEditForm.mintProjectID = mintProjectID
                    lInvEditForm.InvestorId = lintInvestorID
                    lInvEditForm.mblnIsEditInDataHub = True
                    lInvEditForm.ShowDialog()
                    If Not lInvEditForm.mblnCancelDataHub Then
                        grdData.DisplayLayout.Bands(0).ColumnFilters.ClearAllFilters()
                        'Make the changes in edited row i.e investor. List is retrieved from form where the changed are done.
                        SetChangesInGridRow(lInvEditForm.mlstInvestorDetails, True)
                        'Retrive and replace all the funds of replaced investor.
                        AddNewLinkedFunds(grdData.ActiveRow.GetCellValue("InvestorID"))
                        MakeFlagEditInvestor(lintInvestorID)
                    End If
                Else
                    If (mclsDataHubManager.CheckRecordExistence("fund", lintFundID) = False) Then
                        MessageBox.Show(MessageManager.GetMessage("RECORD_DELETED/MODIFIED").ToString, m_strMsgBoxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information)
                        Exit Sub
                    End If
                    lFundEditForm = New AddEditFund
                    lFundEditForm.mintProjectID = mintProjectID
                    lFundEditForm.FundId = lintFundID
                    lFundEditForm.mblnIsEditInDataHub = True
                    lFundEditForm.ShowDialog()
                    If Not lFundEditForm.mblnCancelDataHub Then
                        grdData.DisplayLayout.Bands(0).ColumnFilters.ClearAllFilters()
                        If lFundEditForm.mlstFundDetails Is Nothing Then Exit Sub
                        'Make the changes in edited row i.e fund. List is retrieved from form where the changes are done.
                        SetChangesInGridRow(lFundEditForm.mlstFundDetails, False)
                        'Retrieve all the investor(s) related to this fund.
                        AddInvestorsOfFund(grdData.ActiveRow.GetCellValue("FundID"))
                        MakeFlagEditFund(lintFundID)
                    End If
                End If
            End If
            grdData.Update()
            grdData.UpdateData()
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            lInvEditForm = Nothing
            lFundEditForm = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="llstUpdateRow"></param>
    ''' <param name="lblnInvestorRow"></param>
    ''' <remarks></remarks>
    Private Sub SetChangesInGridRow(ByVal llstUpdateRow As List(Of Crystal.Common.Model.AddNewInvestor), ByVal lblnInvestorRow As Boolean)
        Dim lstrIntendSpace As String = "     "
        Dim grow As UltraGridRow = grdData.ActiveRow
        If llstUpdateRow Is Nothing Then Exit Sub
        'grdData.EventManager.SetEnabled(Infragistics.Win.UltraWinGrid.GridEventIds.InitializeRow, False)
        'grdData.EventManager.SetEnabled(Infragistics.Win.UltraWinGrid.GridEventIds.AfterCellUpdate, False)
        Try
            'update the selected row fields.
            If lblnInvestorRow Then
                grow.Cells("Name").Value = llstUpdateRow(0).InvestorName
                grow.Cells("InvestorName").Value = llstUpdateRow(0).InvestorName
                grow.Cells("Type").Value = llstUpdateRow(0).Type
                grow.Cells("Turnover").Value = llstUpdateRow(0).Turnover
                grow.Cells("Country").Value = llstUpdateRow(0).Country
                grow.Cells("InvStatusCode").Value = llstUpdateRow(0).InvStatusCode
                grow.Cells("Style").Value = llstUpdateRow(0).Style
                grow.Cells("Parent").Value = llstUpdateRow(0).Parent
                grow.Cells("Head Investor").Value = llstUpdateRow(0).HeadInvestor
                grow.Cells("City").Value = llstUpdateRow(0).City
                grow.Cells("State").Value = llstUpdateRow(0).State
                grow.Cells("Region").Value = llstUpdateRow(0).Region
                grow.Cells("Status").Value = llstUpdateRow(0).Status

                'update the row of active cell fields.
            Else
                grow.Cells("Name").Value = lstrIntendSpace + llstUpdateRow(0).FundName
                grow.Cells("FundName").Value = llstUpdateRow(0).FundName
                grow.Cells("Type").Value = llstUpdateRow(0).Type
                grow.Cells("Turnover").Value = llstUpdateRow(0).Turnover
                grow.Cells("Country").Value = llstUpdateRow(0).Country
                grow.Cells("InvStatusCode").Value = llstUpdateRow(0).InvStatusCode
                grow.Cells("Status").Value = llstUpdateRow(0).Status
                'update the row of active cell fields.
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            grdData.EventManager.SetEnabled(Infragistics.Win.UltraWinGrid.GridEventIds.InitializeRow, True)
            grdData.EventManager.SetEnabled(Infragistics.Win.UltraWinGrid.GridEventIds.AfterCellUpdate, True)
        End Try
    End Sub

    ''' <summary>
    ''' To hide the selected columns from the grid
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuHide_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuHide.Click
        'Cancel out the cut operation
        CancelOutCutOperation()
        Dim lblnCanHide As Boolean = True
        Dim lobjData As CurrentDataSources = Nothing
        Dim lstrColName As String
        Try
            'Traverse each selected column and hide the column and also the associated date column, if exists
            For Each lCol As ColumnHeader In grdData.Selected.Columns
                lstrColName = lCol.Caption
                lobjData = mstCurrentDataSources.Find(Function(p) p.SourceName = lstrColName)
                If lobjData IsNot Nothing Then
                    If mstAllDataSourceDateCols.Contains(lobjData.SourceDate) Then
                        grdData.Rows.Band.Columns(lobjData.SourceDate).Hidden = True
                    End If
                    If lobjData.SourceTypeCode = SourceTypeCode.PBC.ToString Then
                        grdData.Rows.Band.Columns(lobjData.PublicSourceCol).Hidden = True
                        grdData.Rows.Band.Columns(lobjData.PublicFilingDateCol).Hidden = True
                    End If
                    If lobjData.SourceTypeCode = SourceTypeCode.RSH.ToString Then
                        grdData.Rows.Band.Columns(lobjData.ResearchSourceCol).Hidden = True
                    End If
                ElseIf lstrColName.StartsWith(mstrFLCurrentListingPrefix) AndAlso menmScreenType = DataHubScreenType.FinalizeList Then
                    grdData.Rows.Band.Columns(lstrColName.Replace(mstrFLCurrentListingPrefix, mstrFLSuggestedFinalListingPrefix)).Hidden = True
                End If
                lCol.Column.Hidden = True
            Next
            'Unselect all the selected columns
            grdData.Selected.Columns.Clear()
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            lobjData = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuAddNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuAddNew.Click
        'Cancel out the cut operations
        CancelOutCutOperation()
        Dim lAddNewColumn As AddNewColumn
        Dim llstNewColumns As List(Of String)
        Dim lobjCurrentDataSources As CurrentDataSources = Nothing
        Dim dtGridData As DataTable
        Dim lclsCLM As New ColumnListManager
        Try
            lAddNewColumn = New AddNewColumn
            lAddNewColumn.mintProjectID = mintProjectID
            If menmScreenType = DataHubScreenType.FinalizeList Then
                lAddNewColumn.mblnFLScreen = True
            Else
                lAddNewColumn.mblnFLScreen = False
            End If
            'Open dialog to add new column.
            lAddNewColumn.ShowDialog()
            If lAddNewColumn.mlstNewAddedColumns IsNot Nothing Then
                AddNewColumnsDataHub(lAddNewColumn.mlstNewAddedColumns)
                'dtGridData = CType(grdData.DataSource, DataTable)
                'If Not menmScreenType = DataHubScreenType.FinalizeList Then
                '    Dim lintLockedColCount As Integer = GetOrdinal()
                '    For Each lobjCurrentDataSource As CurrentDataSources In lAddNewColumn.mlstNewAddedColumns
                '        dtGridData.Columns.Add(lobjCurrentDataSource.SourceName)
                '        grdData.Rows.Band.Columns(lobjCurrentDataSource.SourceName).CellActivation = Activation.NoEdit
                '        If marrDateSuppertedSourceTypes.Contains(lobjCurrentDataSource.ESourceCode) Then
                '            dtGridData.Columns.Add(lobjCurrentDataSource.SourceDate, GetType(Date))
                '            grdData.Rows.Band.Columns(lobjCurrentDataSource.SourceDate).CellActivation = Activation.NoEdit
                '        End If
                '        'dtGridData.Columns(lobjCurrentDataSource.SourceName).SetOrdinal(lintLockedColCount)
                '        lobjCurrentDataSource.EntityID = lclsCLM.GetEntityID(lobjCurrentDataSource.SourceName.ToString)
                '        'mstCurrentDataSources.Add(lobjCurrentDataSource)
                '        'mstEditableDataSourceNameCols.Add(lobjCurrentDataSource.SourceName.ToString)
                '        If lobjCurrentDataSource.IsND Or lobjCurrentDataSource.IsNIL Then
                '            SetAppereanceHeader(lobjCurrentDataSource.SourceName)
                '        End If
                '        'UpdateColumnRelatedData(lobjCurrentDataSource, False)
                '        lintLockedColCount = lintLockedColCount + 1
                '        grdData.Rows.Band.Columns(lobjCurrentDataSource.SourceName).Header.VisiblePosition = lintLockedColCount
                '        If marrDateSuppertedSourceTypes.Contains(lobjCurrentDataSource.ESourceCode) Then
                '            grdData.Rows.Band.Columns(lobjCurrentDataSource.SourceDate).Header.VisiblePosition = lintLockedColCount + 1
                '        End If
                '    Next
                'Else
                '    Dim lintVisiblePosition As Integer = 0
                '    For Each lobjCurrentDataSource As CurrentDataSources In lAddNewColumn.mlstNewAddedColumns
                '        lintVisiblePosition = CheckDataSource(lobjCurrentDataSource)
                '        If lintVisiblePosition > 0 Then
                '            dtGridData.Columns.Add(lobjCurrentDataSource.SourceName)
                '            grdData.Rows.Band.Columns(lobjCurrentDataSource.SourceName).CellActivation = Activation.NoEdit
                '            If marrDateSuppertedSourceTypes.Contains(lobjCurrentDataSource.ESourceCode) Then
                '                dtGridData.Columns.Add(lobjCurrentDataSource.SourceDate, GetType(Date))
                '                grdData.Rows.Band.Columns(lobjCurrentDataSource.SourceDate).CellActivation = Activation.NoEdit
                '            End If
                '            lobjCurrentDataSource.EntityID = lclsCLM.GetEntityID(lobjCurrentDataSource.SourceName.ToString)
                '            If lobjCurrentDataSource.IsND Or lobjCurrentDataSource.IsNIL Then
                '                SetAppereanceHeader(lobjCurrentDataSource.SourceName)
                '            End If
                '            'UpdateColumnRelatedData(lobjCurrentDataSource, False)
                '            lintVisiblePosition = lintVisiblePosition + 1
                '            grdData.Rows.Band.Columns(lobjCurrentDataSource.SourceName).Header.VisiblePosition = lintVisiblePosition
                '            If marrDateSuppertedSourceTypes.Contains(lobjCurrentDataSource.ESourceCode) Then
                '                grdData.Rows.Band.Columns(lobjCurrentDataSource.SourceDate).Header.VisiblePosition = lintVisiblePosition + 1
                '            End If
                '        End If
                '    Next
                'End If
            End If

        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            lAddNewColumn = Nothing
            llstNewColumns = Nothing
            lobjCurrentDataSources = Nothing
            lclsCLM = Nothing
        End Try
    End Sub

    Private Sub FocusOnAddedColumn(ByVal lstrWorkingCol As String)
        grdData.Focus()
        grdData.ActiveColScrollRegion.ScrollColIntoView(grdData.DisplayLayout.Rows.Band.Columns(lstrWorkingCol), True)
        grdData.DisplayLayout.Rows.Band.Columns(lstrWorkingCol).Header.Activated = True
        For Each lSelectedCol As ColumnHeader In grdData.Selected.Columns
            lSelectedCol.Selected = False
        Next
        'grdData.DisplayLayout.Rows.Band.Columns(lstrWorkingCol).sele = True
    End Sub

    ''' <summary>
    ''' To edit the details of a column
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuEdit.Click
        'Cancel out the operations
        CancelOutCutOperation()
    End Sub

    ''' <summary>
    ''' To delete the selected columns
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuDelete.Click, mnuLockDelete.Click
        Dim lstrEntityIDs As StringBuilder = Nothing
        Dim lstrDataEntityNames As StringBuilder = Nothing
        Dim lobjCurrentDataSources As CurrentDataSources = Nothing
        Dim lstrSelectedCol As String
        Dim enmResult As DBResult
        Dim lstrMessage As String = ""
        Dim lblnCanGoAhead As Boolean = True
        Dim ldtData As DataTable = Nothing
        'Cance out any Cut operations, if exist
        CancelOutCutOperation()
        Try
            lstrEntityIDs = New StringBuilder
            lstrDataEntityNames = New StringBuilder
            'Store the Data Source names and EntityIDs to be deleted
            For Each lCol As ColumnHeader In grdData.Selected.Columns
                If mstAllDataSourceNameCols.Contains(lCol.Caption) = False AndAlso mstAllDataSourceDateCols.Contains(lCol.Caption) = False Then Continue For
                lstrSelectedCol = lCol.Caption
                lobjCurrentDataSources = mstCurrentDataSources.Find(Function(p) p.SourceName = lstrSelectedCol)
                If lobjCurrentDataSources Is Nothing Then
                    lobjCurrentDataSources = mstCurrentDataSources.Find(Function(p) p.SourceDate = lstrSelectedCol)
                End If
                lstrEntityIDs.Append(lobjCurrentDataSources.EntityID.ToString + ",")
                lstrDataEntityNames.Append(lobjCurrentDataSources.SourceName + ",")
            Next
            If lstrEntityIDs.Length > 0 Then
                lstrEntityIDs.Length = lstrEntityIDs.Length - 1
                lstrDataEntityNames.Length = lstrDataEntityNames.Length - 1
                'Confirm from the user
                If MessageBox.Show(MessageManager.GetMessage(DBResult.DE_COL_DEL_CNFRMTN.ToString), CommonCLL.mstrMsgBoxCaption, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) <> DialogResult.Yes Then
                    Exit Sub
                End If
            Else
                Exit Sub
            End If

            SaveData(lblnCanGoAhead, False)
            If lblnCanGoAhead Then
                'Delete the selected data sources
                mclsDataHubManager.DeleteDataEntity(lstrEntityIDs.ToString, enmResult, lstrMessage)
                If enmResult = DBResult.SUCCESS Then
                    'Delete the data sources from the grid
                    DeleteDataEntityFromFrontEnd(lstrDataEntityNames.ToString, grdData.DataSource)
                    'To remove FL parent group columns
                    ldtData = grdData.DataSource
                    AddRemoveFLColumns(ldtData)
                ElseIf enmResult = DBResult.FAILED Then
                    Me.ShowMessageBox(DBResult.DE_COL_DEL_FAILED, lstrMessage)
                Else
                    Me.ShowMessageBox(enmResult)
                End If
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            lstrEntityIDs = Nothing
            lobjCurrentDataSources = Nothing
            lstrDataEntityNames = Nothing
            ldtData = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' To load the eSource Mapping screen for the selected eSource
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuLoadMapping_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuLoadMapping.Click
        'Cance out Cut operations
        CancelOutCutOperation()
        Dim lfrmImporteSource As ImporteSource
        Dim lblnIsAlreadyOpen As Boolean = False
        'Get the selected Data Source
        Dim lobjCurrentEntity As CurrentDataSources = mstCurrentDataSources.Find(Function(p) p.SourceName = mstrRightClickColName)
        Dim lstrImporteSourceName As String = "Crystal - " + mstrClientName + " - " + mstrProjectName + " - " + lobjCurrentEntity.SourceName + " - " + TitleManager.GetTitle("ImporteSource")
        'Check if an instance is already opened for the same
        FocusOnExistingInstance(lstrImporteSourceName, "DataHub", Me.WindowState, lblnIsAlreadyOpen)
        If lobjCurrentEntity IsNot Nothing AndAlso lblnIsAlreadyOpen = False Then
            'Disable the DataHub screen
            spcDataHub.Enabled = False
            'Make an instance of Import eSource screen
            lfrmImporteSource = New ImporteSource(Nothing, Nothing, lobjCurrentEntity.EntityID, mintProjectID)
            If lfrmImporteSource.mstrScreenStatus.Equals("") = False Then
                MessageBox.Show(lfrmImporteSource.mstrScreenStatus, MessageManager.GetMessage("CRYSTAL"), MessageBoxButtons.OK, MessageBoxIcon.Information)
                lfrmImporteSource.Close()
                lfrmImporteSource.Dispose()
                ReEnableDataHub(False)
            Else
                'Handler that will be used to reenable the data hub screen
                AddHandler lfrmImporteSource.ReEnableDataHub, AddressOf ReEnableDataHub
                'Set the class level variables
                lfrmImporteSource.mstrMappedInvName = mstrMappedInvName
                lfrmImporteSource.mstrMappedFundName = mstrMappedFundName
                lfrmImporteSource.marrExcludedFromFilters = marrExcludedFromFilters
                lfrmImporteSource.mintClientID = mintClientID
                lfrmImporteSource.mintProjectID = mintProjectID
                lfrmImporteSource.mintListingID = lobjCurrentEntity.ListingID
                lfrmImporteSource.mstrClientName = mstrClientName
                lfrmImporteSource.mstrProjectName = mstrProjectName
                lfrmImporteSource.mstrListingName = lobjCurrentEntity.ListingName
                lfrmImporteSource.mstrDataSourceName = lobjCurrentEntity.ESourceName
                lfrmImporteSource.mstrSourceTypeCode = lobjCurrentEntity.SourceTypeCode
                lfrmImporteSource.menmSourceTypeCode = DirectCast([Enum].Parse(GetType(SourceTypeCode), lobjCurrentEntity.SourceTypeCode), SourceTypeCode)
                lfrmImporteSource.WindowState = FormWindowState.Maximized
                lfrmImporteSource.menmSnapshotType = SnapshotType.Complete
                'Open the Import eSource screen
                lfrmImporteSource.Show()
            End If
        End If
    End Sub

    ''' <summary>
    ''' Call Unlock data source functionality
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuUnlock_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuUnlock.Click
        'Cancel out the cut operations
        CancelOutCutOperation()
        CallUnlockFunctionality(False, False, True)
    End Sub

    ''' <summary>
    ''' Call Lock data source funtionality
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuLock_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuLock.Click
        'GetAccessDataSourceStatus
        'Cancel out the cut operations
        CancelOutCutOperation()
        Dim lblnCanGoAhead As Boolean = True
        Dim lobjCurrentDataSources As CurrentDataSources
        Dim lstDataSourceStatus As IList(Of SourceEntityAccessStatus) = Nothing
        Try
            If mstEditableDataSourceNameCols.Contains(mstrRightClickColName) Then
                lobjCurrentDataSources = mstCurrentDataSources.Find(Function(p) p.SourceName = mstrRightClickColName)
            Else
                lobjCurrentDataSources = mstCurrentDataSources.Find(Function(p) p.SourceDate = mstrRightClickColName)
            End If
            If lobjCurrentDataSources IsNot Nothing Then
                lstDataSourceStatus = mclsDataHubManager.GetAccessDataSourceStatus(lobjCurrentDataSources.EntityID, CommonCLL.UserID)
                'If there is any data source which is already locked by some other user, then inform the user about it
                If lstDataSourceStatus.Count > 0 Then
                    Me.ShowMessageBox(DBResult.DE_ENTITY_IN_USE, lstDataSourceStatus.Item(0).UserFullName)
                    Exit Sub
                End If
            End If
            If mstCurrentDataSources.Find(Function(p) p.AccessStatus = SourceAccessbility.Locked.ToString) IsNot Nothing Then
                CallUnlockFunctionality(False, False, lblnCanGoAhead)
            End If
            If lblnCanGoAhead Then
                LockUnlockEntities(True, False)
                FocusOnFirstLockedCell(True)
            End If
            If mstCurrentDataSources IsNot Nothing Then
                For Each lstCurrentDataSource As CurrentDataSources In mstCurrentDataSources
                    If lstCurrentDataSource.IsND Or lstCurrentDataSource.IsNIL Then
                        SetAppereanceHeader(lstCurrentDataSource.SourceName)
                    End If
                Next
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            lobjCurrentDataSources = Nothing
            lstDataSourceStatus = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' To remove the rows i.e. Investor/Funds
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuRowDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuRowDelete.Click
        'To cancel out any pending Cut operations
        CancelOutCutOperation()
        Dim lMsgBoxResult As MsgBoxResult
        Dim lblnIsDelete As Boolean = True
        'Ask the user if he wishes to delete/remove(Delete deletes it from Master DB, removes from Project DB)
        lMsgBoxResult = CYMessageBox.Show("Do you wish to remove records from your project or delete from the database?", "Delete", CYMessageBox.CustomButtons.RemoveDelete, CYMessageBox.CYIcon.Warning)
        If lMsgBoxResult = DialogResult.No Then
            lblnIsDelete = False
        End If

        Dim lstrInvestorDataToDelete As StringBuilder = Nothing
        Dim lstrFundDataToDelete As StringBuilder = Nothing
        Dim lstrReferencedInvDataToDelete As StringBuilder = Nothing
        Dim lstrReferencedFundDataToDelete As StringBuilder = Nothing
        Dim lblnIsFirstSelectedRow As Boolean = True
        Dim lstrColToDeal As String = ""
        Dim lblnIsInvestor As Boolean = False
        Dim lstDataSourceInvStatus As List(Of LinkingDetails) = Nothing
        Dim lstDataSourceFundStatus As List(Of LinkingDetails) = Nothing
        Dim enmResult As DBResult
        Dim lstrErrorMessage As String = ""
        Dim lstrDeletingType As String = ""
        Dim lintInvestorRowIndex As Integer
        Dim lintFundLinkCount As Integer
        Dim lobjFundStatus As LinkingDetails = Nothing
        Dim larrInvestorData() As String
        Dim lUltraGridRow As UltraGridRow = Nothing
        Dim lintSelectedRowCounter As Integer
        Dim lintSelectedRowLastFundIndex As Integer
        Dim lintSelectedRowIndex As Integer
        Dim lblnCanDelete As Boolean
        Try
            lstrInvestorDataToDelete = New StringBuilder
            lstrFundDataToDelete = New StringBuilder
            lstrReferencedInvDataToDelete = New StringBuilder
            lstrReferencedFundDataToDelete = New StringBuilder
            'Traverse all selected rows
            For Each lUltraRow As UltraGridRow In grdData.Selected.Rows
                If lblnIsFirstSelectedRow Then
                    lblnIsFirstSelectedRow = False
                    'Check if its an Investor
                    If lUltraRow.GetCellValue("LinkID") = 0 Then
                        lblnIsInvestor = True
                        lstrColToDeal = "InvestorID"
                        lstrDeletingType = "investor"
                    Else
                        lblnIsInvestor = False
                        lstrColToDeal = "LinkID"
                        lstrDeletingType = "fund"
                    End If
                End If
                'Store the InvestorID/FundID in a variable
                If lblnIsInvestor Then
                    lstrInvestorDataToDelete.Append(lUltraRow.GetCellValue(lstrColToDeal).ToString + ",")
                    lintInvestorRowIndex = lUltraRow.Index + 1
                    While lintInvestorRowIndex < grdData.Rows.Count
                        If grdData.Rows(lintInvestorRowIndex).GetCellValue("LinkID") = 0 Then Exit While
                        lstrFundDataToDelete.Append(grdData.Rows(lintInvestorRowIndex).GetCellValue("LinkID").ToString + ",")
                        lintInvestorRowIndex += 1
                    End While
                Else
                    lstrFundDataToDelete.Append(lUltraRow.GetCellValue(lstrColToDeal).ToString + ",")
                End If
            Next
            If lstrInvestorDataToDelete.Length > 0 Then
                lstrInvestorDataToDelete.Length = lstrInvestorDataToDelete.Length - 1
            End If
            If lstrFundDataToDelete.Length > 0 Then
                lstrFundDataToDelete.Length = lstrFundDataToDelete.Length - 1
            End If
            'If user wants to delete
            If lMsgBoxResult = MsgBoxResult.Yes Then
                lstDataSourceInvStatus = New List(Of LinkingDetails)
                lstDataSourceFundStatus = New List(Of LinkingDetails)
                'Get the Investor/Funds which have references i.e. Already being used
                mclsDataHubManager.GetDeleteRemoveInvFundStatus(mintProjectID, lstrInvestorDataToDelete.ToString, lstrFundDataToDelete.ToString, lstDataSourceInvStatus, lstDataSourceFundStatus)
                'Store the Investor references in a variable
                For Each lobjInvDetails As LinkingDetails In lstDataSourceInvStatus
                    lstrReferencedInvDataToDelete.Append(lobjInvDetails.InvestorID.ToString + ",")
                Next
                lintFundLinkCount = lstDataSourceFundStatus.Count - 1
                lobjFundStatus = Nothing
                larrInvestorData = lstrInvestorDataToDelete.ToString.Split(",")
                While lintFundLinkCount >= 0
                    If larrInvestorData.Contains(lstDataSourceFundStatus(lintFundLinkCount).InvestorID.ToString) Then
                        If lstDataSourceInvStatus.Find(Function(p) p.InvestorID = lstDataSourceFundStatus(lintFundLinkCount).InvestorID) Is Nothing Then
                            lstDataSourceFundStatus.RemoveAt(lintFundLinkCount)
                        End If
                    End If
                    lintFundLinkCount -= 1
                End While
                'Store the Fund references in a variable
                For Each lobjFundDetails As LinkingDetails In lstDataSourceFundStatus
                    lstrReferencedFundDataToDelete.Append(lobjFundDetails.LinkID.ToString + ",")
                Next
                If lstrReferencedInvDataToDelete.Length > 0 Then
                    lstrReferencedInvDataToDelete.Length = lstrReferencedInvDataToDelete.Length - 1
                End If
                If lstrReferencedFundDataToDelete.Length > 0 Then
                    lstrReferencedFundDataToDelete.Length = lstrReferencedFundDataToDelete.Length - 1
                End If
            Else
                lstrReferencedInvDataToDelete.Append("")
                lstrReferencedFundDataToDelete.Append("")
            End If
            'If the selection is delete and there are references; ask the user if he wants to mark such records for Deletion
            If lblnIsDelete AndAlso (lstrReferencedInvDataToDelete.Length > 0 OrElse lstrReferencedFundDataToDelete.Length > 0) Then
                If MessageBox.Show("Warning: The selected " + lstrDeletingType + "(s) is currently in use and cannot be deleted. Do you wish to mark it for automatic deletion in the future? Yes/No?", CommonCLL.mstrMsgBoxCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then
                    Exit Sub
                End If
            Else
                'If delete is selected, Inform that the content will be removed from the Master DB
                If lblnIsDelete AndAlso (lstrInvestorDataToDelete.Length > 0 OrElse lstrFundDataToDelete.Length > 0) Then
                    If MessageBox.Show("Warning: Deleting the " + lstrDeletingType + "(s) will remove it from the central database and it will no longer be available for any client. Do you wish to proceed?", CommonCLL.mstrMsgBoxCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then
                        Exit Sub
                    End If
                End If
            End If
            'Delete the Investors/Funds from DB and mark the referenced as delete.
            mclsDataHubManager.DeleteRemoveInvFund(mintProjectID, lstrInvestorDataToDelete.ToString, lstrReferencedInvDataToDelete.ToString, lstrFundDataToDelete.ToString, lstrReferencedFundDataToDelete.ToString, lblnIsDelete, enmResult, lstrErrorMessage)
            If enmResult = DBResult.SUCCESS Then
                lintSelectedRowCounter = grdData.Selected.Rows.Count - 1
                lblnCanDelete = True
                'Traverse the grid and removes the associated funds from the grid too, if the selected row(s) is an Investor
                While lintSelectedRowCounter >= 0
                    lintSelectedRowIndex = grdData.Selected.Rows(lintSelectedRowCounter).Index
                    If grdData.Rows(lintSelectedRowIndex).GetCellValue("LinkID") = 0 Then
                        lintSelectedRowIndex += 1
                        'If there are any references of the fund, then update it's status
                        If lstDataSourceFundStatus IsNot Nothing Then
                            If lstDataSourceFundStatus.Find(Function(p) p.LinkID = grdData.Rows(lintSelectedRowIndex).GetCellValue("LinkID")) IsNot Nothing Then
                                lblnCanDelete = False
                            End If
                        End If
                        For lintSelectedRowLastFundIndex = lintSelectedRowIndex + 1 To grdData.Rows.Count
                            If lintSelectedRowLastFundIndex = grdData.Rows.Count Then Exit For
                            If grdData.Rows(lintSelectedRowLastFundIndex).GetCellValue("LinkID") = 0 Then
                                Exit For
                            End If
                        Next
                        If lintSelectedRowLastFundIndex <> grdData.Rows.Count - 1 Then
                            lintSelectedRowLastFundIndex -= 1
                        End If
                        'Otherwise delete it.
                        While lintSelectedRowLastFundIndex >= lintSelectedRowIndex
                            If lblnCanDelete = False Then
                                MarkEntityDelete(grdData.Rows(lintSelectedRowLastFundIndex))
                            Else
                                RemoveDataFromTrackingTables(grdData.Rows(lintSelectedRowLastFundIndex).GetCellValue("LinkID"), grdData.Rows(lintSelectedRowLastFundIndex).GetCellValue("InvestorID"))
                                grdData.Rows(lintSelectedRowLastFundIndex).Delete(False)
                            End If
                            lintSelectedRowLastFundIndex -= 1
                        End While
                    End If
                    lintSelectedRowCounter -= 1
                End While

                Dim lintDeletingInvestorID As Integer
                Dim lintDeletingLinkID As Integer
                'Traverse the grid and removes the selected rows from the grid too
                lintSelectedRowCounter = grdData.Selected.Rows.Count - 1
                While lintSelectedRowCounter >= 0
                    lblnCanDelete = True
                    lUltraGridRow = grdData.Selected.Rows(lintSelectedRowCounter)
                    lintDeletingInvestorID = lUltraGridRow.GetCellValue("InvestorID")
                    lintDeletingLinkID = lUltraGridRow.GetCellValue("LinkID")
                    lUltraGridRow.Cells("IsCutRow").Value = True
                    'grdData.Rows.GetRowWithListIndex
                    If lUltraGridRow.GetCellValue("LinkID") <> 0 Then
                        'Check if it's a delete operation
                        If lblnIsDelete Then
                            If lstDataSourceFundStatus IsNot Nothing Then
                                'Check if Fund has any references, if yes, then just change the visiblity and status
                                If lstDataSourceFundStatus.Find(Function(p) p.LinkID = lUltraGridRow.GetCellValue("LinkID")) IsNot Nothing Then
                                    lblnCanDelete = False
                                    MarkEntityDelete(lUltraGridRow)
                                Else
                                    'Update the Investor & Managed Fund's positions
                                    SetInvAndManagedFundPositionsForCut(True, lUltraGridRow)
                                    'Otherwise remove it from the grid
                                    lUltraGridRow.Delete(False)
                                    SaveData(True, False)
                                End If
                            End If
                        Else
                            'Update the Investor & Managed Fund's positions
                            SetInvAndManagedFundPositionsForCut(True, lUltraGridRow)
                            'Otherwise check if its a Remove Operation
                            lUltraGridRow.Delete(False)
                            SaveData(True, False)
                            'If lstUpdatingInvestors.Contains(lintLinkedInvestors) = False Then
                            '    lstUpdatingInvestors.Add(lintLinkedInvestors)
                            'End If
                            'If it's a fund deletion, then update the positions of the relevant Managed Fund and Investor
                        End If
                    Else
                        'Check if it's a delete operation
                        If lblnIsDelete Then
                            If lstDataSourceInvStatus IsNot Nothing Then
                                'Check if Inv has any references, if yes, then just change the visiblity and status
                                If lstDataSourceInvStatus.Find(Function(p) p.InvestorID = lUltraGridRow.GetCellValue("InvestorID")) IsNot Nothing Then
                                    lblnCanDelete = False
                                    MarkEntityDelete(lUltraGridRow)
                                Else
                                    'Otherwise remove it from the grid
                                    lUltraGridRow.Delete(False)
                                End If
                            End If
                        Else
                            'Otherwise check if its a Remove Operation
                            lUltraGridRow.Delete(False)
                        End If
                    End If
                    If lblnCanDelete Then
                        RemoveDataFromTrackingTables(lintDeletingLinkID, lintDeletingInvestorID)
                    End If
                    lintSelectedRowCounter -= 1
                End While
                grdData.Update()
                grdData.UpdateData()
                CType(grdData.DataSource, DataTable).AcceptChanges()

                'If the delete row is failed, inform the user
            ElseIf enmResult = DBResult.FAILED Then
                Me.ShowMessageBox(DBResult.DH_DELETEROW_FAIL, lstrErrorMessage)
            Else
                Me.ShowMessageBox(enmResult)
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            lstrInvestorDataToDelete = Nothing
            lstrFundDataToDelete = Nothing
            lstrReferencedInvDataToDelete = Nothing
            lstrReferencedFundDataToDelete = Nothing
            lstDataSourceInvStatus = Nothing
            lstDataSourceFundStatus = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' To remove specific value data from the tracking tables
    ''' </summary>
    ''' <param name="pintLinkID"></param>
    ''' <param name="pintInvestorID"></param>
    ''' <remarks></remarks>
    Private Sub RemoveDataFromTrackingTables(ByVal pintLinkID As Integer, ByVal pintInvestorID As Integer)
        mstDataSourceChanges.RemoveAll(Function(p) p.LinkID = pintLinkID AndAlso p.InvestorID = pintInvestorID)
        mstPreviousProjectChanges.RemoveAll(Function(p) p.LinkID = pintLinkID AndAlso p.InvestorID = pintInvestorID)
        mstLinkingChanges.RemoveAll(Function(p) p.NewLinkID = pintLinkID OrElse p.OldLinkID = pintLinkID)
    End Sub

    ''' <summary>
    ''' Perform the cut operation
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuCut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuCut.Click
        PerformCutOperation()
    End Sub

    ''' <summary>
    ''' Perform the insert operation
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuInsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuInsert.Click
        PerformInsertOperation()
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuAddNewInvestor_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuAddNewInvestor.Click
        'Cancel out the cut operations
        CancelOutCutOperation()
        Dim lfrmAddModifyInvestor As New frmAddModifyInvestor
        Dim ldtGridData As DataTable
        Dim lstrInvSearchSplitText() As String
        Try
            ldtGridData = New DataTable
            mdtNewRowData = New DataTable
            ldtGridData = CType(grdData.DataSource, DataTable)
            lfrmAddModifyInvestor.Text = TitleManager.GetTitle("AddModifyInvestor")
            lfrmAddModifyInvestor.mintProjectID = mintProjectID
            lfrmAddModifyInvestor.mintRowNumber = Convert.ToInt32(ldtGridData.Compute("max(RowNumber)", String.Empty))
            'Show the form to add new investor.
            lfrmAddModifyInvestor.ShowDialog()
            'Add New investor to grid.
            If lfrmAddModifyInvestor.mlstInvestorDetails IsNot Nothing Then
                If lfrmAddModifyInvestor.mlstInvestorDetails(0).Name IsNot Nothing Then
                    mlstFundInvestor = lfrmAddModifyInvestor.mlstInvestorDetails
                    'Add new linked fund to the investor
                    AddNewLinkedFunds(lfrmAddModifyInvestor.mlstInvestorDetails(0).InvestorID)
                    'Default selection of controls on addition of new fund or investor
                    DefaultSelectionOnNewInvestor()
                    'Select the newly added investor.
                    SelectInvestorRow(lfrmAddModifyInvestor.mlstInvestorDetails(0).InvestorID)
                    lstrInvSearchSplitText = {lfrmAddModifyInvestor.mlstInvestorDetails(0).Name}
                    grdData.DisplayLayout.Bands(0).ColumnFilters.ClearAllFilters()
                    'rootBand.ColumnFilters.ClearAllFilters()
                    Me.Invoke(New AccessControl(AddressOf SetSearchFilterResultText), SearchResultType.CustomSearch)
                    ConductInvestorOnlyCustomSearch(SearchedTextOperators.AND, lstrInvSearchSplitText, False)
                End If
            End If
            grdData.Update()
            grdData.UpdateData()
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            lfrmAddModifyInvestor = Nothing
            ldtGridData = Nothing
            lstrInvSearchSplitText = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub SelectInvestorRow(ByVal intInvestorId As Integer)
        Dim colRow As UltraGridRow = Me.grdData.Rows.OfType(Of UltraGridRow)().ToList().Find(Function(row) row.Cells("InvestorID").Text.Equals(intInvestorId.ToString, StringComparison.CurrentCultureIgnoreCase))
        If colRow IsNot Nothing Then
            If colRow.GetCellValue("LinkID") = 0 Then
                colRow.Selected = True
                colRow.Activated = True
            End If
        End If
    End Sub

    ''' <summary>
    ''' Event to add the new Fund.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuAddNewFund_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuAddNewFund.Click
        'Cancel out the cut operations
        CancelOutCutOperation()
        Dim lfrmAddEditFund As New AddEditFund
        Dim ldtGridData As DataTable
        Dim lintInvestorID As Integer = 0
        'Dim lintFundID As Integer = 0
        Dim lstrInvestorName As String = String.Empty
        Dim lstrInvSearchSplitText() As String
        Dim lstrFundSearchSplitText() As String
        Try
            ldtGridData = New DataTable
            ldtGridData = CType(grdData.DataSource, DataTable)
            lfrmAddEditFund.Text = TitleManager.GetTitle("AddEditFund")
            lfrmAddEditFund.mintProjectID = mintProjectID
            'Get the investor id and InvestorName of the selected fund.
            GetInvestorID(lintInvestorID, lstrInvestorName)
            lfrmAddEditFund.mintInvestorID = lintInvestorID
            'lfrmAddEditFund.mintFundID = lintFundID
            lfrmAddEditFund.mstrInvestorName = lstrInvestorName
            lfrmAddEditFund.mintRowNumber = Convert.ToInt32(ldtGridData.Compute("max(RowNumber)", String.Empty))
            'Show the form to add new fund.
            lfrmAddEditFund.ShowDialog()
            If lfrmAddEditFund.mlstFundDetails IsNot Nothing Then
                mlstFundInvestor = lfrmAddEditFund.mlstFundDetails
                'Retrieve all the investor related to new added fund.
                AddInvestorsOfFund(mlstFundInvestor(0).FundID)
                'Set the properties of control of the form.
                If menmScreenType = DataHubScreenType.FinalizeList Then
                    MakeFlagNewFund(mlstFundInvestor(0).FundID, lintInvestorID)
                End If
                RecallDataChanges(False)
                DefaultSelectionOnNewInvestor()
                'SelectFundRow(mlstFundInvestor(0).FundID)
                grdData.Selected.Rows.Clear() '= Nothing
                lstrInvSearchSplitText = mstrInvestorNameSearch.Split("|")
                lstrFundSearchSplitText = {mlstFundInvestor(0).FundName}
                grdData.DisplayLayout.Bands(0).ColumnFilters.ClearAllFilters()
                Me.Invoke(New AccessControl(AddressOf SetSearchFilterResultText), SearchResultType.CustomSearch)
                ConductFundCustomSearch(mstrInvestorNameSearch, SearchedTextOperators.AND, SearchedTextOperators.AND, lstrInvSearchSplitText, lstrFundSearchSplitText, False)
            End If
            grdData.Update()
            grdData.UpdateData()
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            ldtGridData = Nothing
            lfrmAddEditFund = Nothing
            lstrFundSearchSplitText = Nothing
            lstrInvSearchSplitText = Nothing
            mstrInvestorNameSearch = String.Empty
        End Try
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="pintFundID"></param>
    ''' <param name="pintInvestorID"></param>
    ''' <remarks></remarks>
    Private Sub MakeFlagNewFund(ByVal pintFundID As Integer, ByVal pintInvestorID As Integer)
        mclsDataHubManager.MakeFlagNewFund(pintInvestorID, pintFundID, mintProjectID, DataChangeFlagType.ADD.ToString)
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="pintInvestorID"></param>
    ''' <remarks></remarks>
    Private Sub MakeFlagNewInvestor(ByVal pintInvestorID As Integer)
        mclsDataHubManager.MakeFlagNewInvestor(pintInvestorID, mintProjectID, DataChangeFlagType.ADD.ToString)
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="pintInvestorID"></param>
    ''' <remarks></remarks>
    Private Sub MakeFlagEditInvestor(ByVal pintInvestorID As Integer)
        mclsDataHubManager.MakeFlagNewInvestor(pintInvestorID, mintProjectID, DataChangeFlagType.RPC.ToString)
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="pintFundID"></param>
    ''' <remarks></remarks>
    Private Sub MakeFlagEditFund(ByVal pintFundID As Integer)
        mclsDataHubManager.MakeFlagNewInvestor(pintFundID, mintProjectID, DataChangeFlagType.RPC.ToString)
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="pintOldLinkID"></param>
    ''' <param name="pintNewLinkID"></param>
    ''' <param name="pintInvestorID"></param>
    ''' <remarks></remarks>
    Private Sub AddFlagChangeFund(ByVal pintOldLinkID As Integer, ByVal pintNewLinkID As Integer, ByVal pintInvestorID As Integer)
        mclsDataHubManager.MakeFlagChangeFund(pintInvestorID, pintOldLinkID, pintNewLinkID, mintProjectID, DataChangeFlagType.RPC.ToString)
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub SelectFundRow(ByVal intFundId As Integer)
        Dim colRow As UltraGridRow = Me.grdData.Rows.OfType(Of UltraGridRow)().ToList().Find(Function(row) row.Cells("FundID").Text.Equals(intFundId.ToString, StringComparison.CurrentCultureIgnoreCase))
        If colRow IsNot Nothing Then
            colRow.Selected = True
            colRow.Activated = True
        End If
    End Sub

    ''' <summary>
    ''' Event fires when user wants to add new column.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuAddNewColumn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuAddNewColumn.Click
        'Cancel out the cut operations
        CancelOutCutOperation()
        mnuAddNew.PerformClick()
    End Sub

    ''' <summary>
    ''' To retrieve latest data for the selected previous listings
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuUnlockRetrieve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuUnlockRetrieve.Click
        ConductRetrievePreviousListingData()
    End Sub

    ''' <summary>
    ''' To retrieve latest data for the selected previous listings
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuLockRetrieve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuLockRetrieve.Click
        ConductRetrievePreviousListingData()
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub bgwSqlWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgwSqlWorker.DoWork
        mthdThread = New Thread(AddressOf StartSearch)
        mthdThread.IsBackground = True
        mthdThread.Start()
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub mnuCarryForward_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuCarryForward.Click
        Dim lobjData As CurrentDataSources = Nothing
        Dim lobjCopiedData As PreviousDataSources = Nothing
        Dim lblnCanGoAhead As Boolean = True
        Dim lstrCopiedColumnName As String = String.Empty
        Try
            If menmScreenType = DataHubScreenType.DataEntry Then
                If grdData.Selected.Columns.Count <> 1 Then Exit Sub
                lobjData = mstCurrentDataSources.Find(Function(p) p.AccessStatus = SourceAccessbility.Locked.ToString)
                If lobjData Is Nothing Then
                    MessageBox.Show(MessageManager.GetMessage("DE_LOCK_SINGLE_COL"), BaseClass.crystalCaption, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Exit Sub
                End If
                If grdData.Selected.Columns.Count < 1 Then
                    MessageBox.Show(MessageManager.GetMessage("DE_SELECT_SINGLE_COL"), BaseClass.crystalCaption, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    Exit Sub
                End If
                '        lstrCopiedColumnName = grdData.Selected.Columns(0).Column.Header.Caption
                lobjCopiedData = mstPreviousDataSources.Find(Function(p) p.SourceName = grdData.Selected.Columns(0).Column.Header.Caption)
                'SaveData(lblnCanGoAhead, False)
                'lintIndex = mstCurrentDataSources.Find(Function(p) p.SourceName = grdData.DisplayLayout.Bands(0).Header)
                If lobjCopiedData IsNot Nothing Then
                    If lobjCopiedData.SourceTypeCode = lobjData.SourceTypeCode AndAlso lobjData.ListingName = lobjCopiedData.ListingName AndAlso _
                        lobjCopiedData.ESourceName = lobjData.ESourceName AndAlso grdData.Rows.Band.Columns.Exists(lobjData.SourceName) Then
                        If lblnCanGoAhead Then
                            If grdData.Selected.Columns.Count = 1 Then
                                mclsDataHubManager.CarryForwardColumn(lobjCopiedData.EntityID, lobjData.EntityID, CommonCLL.UserID, mintProjectID)
                                PasteCopiedData(lobjCopiedData.SourceName, lobjData.SourceName)
                            End If
                        End If
                    End If
                End If
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            lobjCopiedData = Nothing
            lobjData = Nothing
        End Try
    End Sub
#End Region

#Region "Ultragrid Export Events"

    ''' <summary>
    ''' To unhide all columns before exporting so that they can be available in the exported excel file.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub UltraGridExcelExporter_ExportStarted(ByVal sender As Object, ByVal e As Infragistics.Win.UltraWinGrid.ExcelExport.ExportStartedEventArgs) Handles UltraGridExcelExporter1.ExportStarted
        For Each column In e.Layout.Bands(0).Columns
            column.Hidden = False
        Next
    End Sub

#End Region

#End Region

#Region "Procedures"

#Region "Load and Save Data"
    ''' <summary>
    ''' To load the data into the grid
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub LoadGridData(ByVal penmDELoadUpType As DELoadUpType)
        Dim ldtData As DataTable = Nothing
        Dim lstrSnapshotPath As String = ""
        Dim lblnIsFromPreviousSnapshot As Boolean = False
        Dim lstSnapshotMissingDataSources As List(Of String) = Nothing
        Dim lintParentColIndex As Int16
        Dim lintActivistColIndex As Int16
        Dim lintColCounter As Integer
        Dim lblnCanRemoveCol As Boolean
        Dim lintPreviousProjectCounter As Int16
        Dim lintRowCounter As Integer
        Dim lintStartColIndex As Integer
        Dim lstrColumnName As String
        Dim ldrSearchedRows() As DataRow = Nothing
        Dim lstDEBasicSource As New List(Of DEBasicSource)
        Dim ldrNDRow As DataRow = Nothing
        Dim lstrSearch As StringBuilder = Nothing
        Dim lblnCanReCalculate As Boolean = True
        Dim ldrRecalculate As DialogResult
        Dim lstResearchSources As List(Of CurrentDataSources) = Nothing
        Dim lblnCanCallCurrentListing As Boolean = False
        Try
            If menmScreenType = DataHubScreenType.FinalizeList Then
                ldrRecalculate = MessageBox.Show(MessageManager.GetMessage(DBResult.FL_RECALCULATE_SUGGESTIONS.ToString), MessageManager.GetMessage("CRYSTAL"), MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                If ldrRecalculate = DialogResult.No Then
                    lblnCanReCalculate = False
                End If
            End If
            Me.Cursor = Cursors.WaitCursor
            Application.DoEvents()
            'spcDataHub.Enabled = False
            grdData.EventManager.SetEnabled(Infragistics.Win.UltraWinGrid.GridEventIds.AfterCellUpdate, False)
            'Get the path of the snapshot, if exists
            'lstrSnapshotPath = "H:\Sukhminder\Projects\Crystal\Code\Project Data\DataEntry\Gold Fields - 11 April 2021 - DE -  - 13_06_2012 22_22_49.txt"
            mclsDataHubManager.GetPreviousSnapshotFilePath(mintProjectID, lstrSnapshotPath, lblnIsFromPreviousSnapshot)
            If lblnIsFromPreviousSnapshot OrElse System.IO.File.Exists(lstrSnapshotPath) = False Then
                penmDELoadUpType = DELoadUpType.CallDatabase
            End If
            If menmScreenType = DataHubScreenType.FinalizeList Then
                If penmDELoadUpType = DELoadUpType.CallDatabase Then
                    lblnCanCallCurrentListing = True
                End If
            End If
            If lstrSnapshotPath.Equals("") = False AndAlso penmDELoadUpType = DELoadUpType.DefaultLoad Then
                'Set the loadup type
                menmDELoadUpType = DELoadUpType.Snapshot
                'Get the other required information e.g. data source & its count, previous data sources, previous projects data etc
                mclsDataHubManager.GetFullData(mintProjectID, mintDataSourcesCount, mintPreviousProjectID, mstrPreviousProjectName, True, Nothing, mstCurrentDataSources, mstPreviousDataSources, mstPreviousProjects, mstrDeliveryListingToSort, lstDEBasicSource, mstListingInformation, lblnCanCallCurrentListing)
                'mdtFLAssociatedData = mclsDataHubManager.GetPreviousFullData(mintProjectID)
                'mclsDataHubManager.GetData(mintProjectID, mintDataSourcesCount, mintPreviousProjectID, mstrPreviousProjectName, True, Nothing, mstCurrentDataSources, mstPreviousDataSources, mstPreviousProjects, mstrDeliveryListingToSort)
            Else
                'If No snapshot is available, load the data from DB
                menmDELoadUpType = DELoadUpType.Database
                'Get the required information from DB
                mclsDataHubManager.GetFullData(mintProjectID, mintDataSourcesCount, mintPreviousProjectID, mstrPreviousProjectName, False, ldtData, mstCurrentDataSources, mstPreviousDataSources, mstPreviousProjects, mstrDeliveryListingToSort, lstDEBasicSource, mstListingInformation, lblnCanCallCurrentListing)
                'mclsDataHubManager.GetData(mintProjectID, mintDataSourcesCount, mintPreviousProjectID, mstrPreviousProjectName, False, ldtData, mstCurrentDataSources, mstPreviousDataSources, mstPreviousProjects, mstrDeliveryListingToSort)
                ChangeDataReaderDataTable(ldtData)
                If ldtData.Rows.Count = 0 Then
                    spcDataHub.Enabled = False
                    Exit Sub
                End If
                RemoveUnnecessaryAssociatedFields(ldtData, mstCurrentDataSources)
                'ChangeDataReaderDataTable(mdtPositionData)
            End If

            'If mstrPreviousProjectName Is Nothing Then mstrPreviousProjectName = ""
            menmSortingOn = SortingOn.Ascending
            'Call to intialize various tracking tables
            PrepareDataSourceDetails()

            'Get the data from the saved snapshot into the datatable
            If menmDELoadUpType = DELoadUpType.Snapshot Then
                LoadSnapshotFromText(ldtData, lstrSnapshotPath)
                'Create previous listing columns if they don't exist in the snapshot
                For Each lstPreviousProjects As PreviousProjects In mstPreviousProjects
                    mstAllPreviousListings.Add(lstPreviousProjects.DeliveryListing)
                    If ldtData.Columns.Contains(lstPreviousProjects.DeliveryListing) = False Then
                        ldtData.Columns.Add(lstPreviousProjects.DeliveryListing, GetType(String))
                        ldtData.Columns(lstPreviousProjects.DeliveryListing).SetOrdinal(ldtData.Columns("Activist").Ordinal)
                    End If
                Next
            End If
            If penmDELoadUpType = DELoadUpType.CallDatabase Then
                For Each lstrColName As String In mstAllDataSourceNameCols
                    If ldtData.Columns.Contains(lstrColName) = False Then
                        ldtData.Columns.Add(lstrColName, GetType(String))
                        ldtData.Columns(lstrColName).SetOrdinal(ldtData.Columns("Parent").Ordinal + 1)
                    End If
                Next
            End If

            'Get the index of certain column that are required in further processing
            'Note: This index is before shifting the columns which is changed further in this procedure
            lintParentColIndex = ldtData.Columns("Parent").Ordinal
            lintActivistColIndex = ldtData.Columns("Activist").Ordinal

            If mstPreviousProjects.Count = 0 Then btnSortPosition.Enabled = False
            'Set the class level datatables to be used later
            If menmDELoadUpType = DELoadUpType.Snapshot Then
                'Remove the obselete previous projects that nomore exists in the database
                lintRowCounter = ldtData.Columns.Count - 1
                While lintRowCounter < lintParentColIndex
                    lstrColumnName = ldtData.Columns(lintRowCounter).ColumnName
                    If lstrColumnName.StartsWith(mstrPreviousProjectName) AndAlso _
                        marrPreviousDataSourceNameCols.Contains(lstrColumnName) = False AndAlso _
                        marrPreviousProjects.Contains(lstrColumnName) = False Then
                        'Contains(mstPreviousProjects.Item(lintRowCounter).DeliveryListing)
                        ldtData.Columns.RemoveAt(lintRowCounter)
                    End If
                    lintRowCounter -= 1
                End While
            End If
            ''Add the generic and client specific sources' columns in the system column list
            lstResearchSources = mstCurrentDataSources.FindAll(Function(p) p.SourceTypeCode = SourceTypeCode.RSH.ToString)
            For Each lstrResearchCol As CurrentDataSources In lstResearchSources
                If ldtData.Columns.Contains(lstrResearchCol.SourceName + mstrClientSpecificSourceColSuffix) Then
                    mstSysColumns.Add(lstrResearchCol.SourceName + mstrClientSpecificSourceColSuffix)
                End If
                If ldtData.Columns.Contains(lstrResearchCol.SourceName + mstrGenericSourceColSuffix) Then
                    mstSysColumns.Add(lstrResearchCol.SourceName + mstrGenericSourceColSuffix)
                End If
            Next

            'If grid is loaded from DB, then remove system columns which are not required
            If menmDELoadUpType = DELoadUpType.Database Then
                'For Each lstrColName As String In marrSysColNamesToRemove
                '    ldtData.Columns.Remove(lstrColName)
                'Next
                'If the grid contains any previous project, then set the columns properly which contain the previous project name e.g. some columns contain $ after 
                'the previous project name which should be replaced with <Space>, that's done here
                If mstrPreviousProjectName.Equals("") = False Then
                    lintStartColIndex = lintParentColIndex
                    While lintStartColIndex < ldtData.Columns.Count
                        If ldtData.Columns(lintStartColIndex).ColumnName.StartsWith(mstrPreviousProjectName) Then
                            ldtData.Columns(lintStartColIndex).ColumnName = ldtData.Columns(lintStartColIndex).Caption.Replace(mstrPreviousProjectName, mstrPreviousProjectName.Substring(0, mstrPreviousProjectName.Length - 1) + " ")
                        End If
                        lintStartColIndex += 1
                    End While
                End If
            End If
            If mstrPreviousProjectName Is Nothing Then
                mstrPreviousProjectName = ""
            ElseIf mstrPreviousProjectName <> "" Then
                mstrPreviousProjectName = mstrPreviousProjectName.Substring(0, mstrPreviousProjectName.Length - 1)
            End If

            If menmDELoadUpType = DELoadUpType.Snapshot Then
                'If being loaded from Snapshot, Remove the obselete data sources of current project that nomore exists in the database
                lintColCounter = ldtData.Columns.Count - 1
                lblnCanRemoveCol = True
                lintRowCounter = ldtData.Columns.Count - 1
                While lintColCounter > lintParentColIndex
                    lblnCanRemoveCol = True
                    If mstSysColumns.Contains(ldtData.Columns(lintColCounter).ColumnName) OrElse _
                        (ldtData.Columns(lintColCounter).ColumnName.Contains(mstrPreviousProjectName) AndAlso mstrPreviousProjectName <> "") OrElse _
                        marrPreviousProjects.Contains(ldtData.Columns(lintColCounter).ColumnName) OrElse mstAttributeSet2.Contains(ldtData.Columns(lintColCounter).ColumnName) _
                    OrElse (mstDataSourceParentGroupPositionCol.Contains(ldtData.Columns(lintColCounter).ColumnName) AndAlso lblnIsFromPreviousSnapshot = False) _
                    OrElse (mstDataSourceParentGroupDateCol.Contains(ldtData.Columns(lintColCounter).ColumnName) AndAlso lblnIsFromPreviousSnapshot = False) _
                    OrElse (ldtData.Columns(lintColCounter).ColumnName.StartsWith(mstrCurrentListingColPrefix) AndAlso lblnIsFromPreviousSnapshot = False) _
                    OrElse (ldtData.Columns(lintColCounter).ColumnName.StartsWith(mstrSuggestedFinalListingColPrefix) AndAlso lblnIsFromPreviousSnapshot = False) Then
                        lintColCounter -= 1
                        Continue While
                    End If
                    If mstCurrentDataSources.Find(Function(p) p.SourceName = ldtData.Columns(lintColCounter).ColumnName) IsNot Nothing Then
                        lblnCanRemoveCol = False
                    ElseIf mstCurrentDataSources.Find(Function(p) p.PublicFilingDateCol = ldtData.Columns(lintColCounter).ColumnName) IsNot Nothing Then
                        lblnCanRemoveCol = False
                    ElseIf mstCurrentDataSources.Find(Function(p) p.PublicSourceCol = ldtData.Columns(lintColCounter).ColumnName) IsNot Nothing Then
                        lblnCanRemoveCol = False
                    ElseIf mstCurrentDataSources.Find(Function(p) p.ResearchSourceCol = ldtData.Columns(lintColCounter).ColumnName) IsNot Nothing Then
                        lblnCanRemoveCol = False
                    ElseIf mstCurrentDataSources.Find(Function(p) p.SourceDate = ldtData.Columns(lintColCounter).ColumnName) IsNot Nothing Then
                        lblnCanRemoveCol = False
                    ElseIf mstCurrentDataSources.Find(Function(p) _
                                                          p.SourceName = ldtData.Columns(lintColCounter).ColumnName.TrimEnd(mstrClientSpecificSourceColSuffix.ToArray) _
                                                          OrElse p.SourceName = ldtData.Columns(lintColCounter).ColumnName.TrimEnd(mstrGenericSourceColSuffix.ToArray) _
                                                          ) IsNot Nothing Then
                        lblnCanRemoveCol = False
                    End If

                    If lblnCanRemoveCol Then
                        If ldtData.Columns.Contains(ldtData.Columns(lintColCounter).ColumnName + mstrFormulaColSuffix) Then
                            ldtData.Columns.Remove(ldtData.Columns(lintColCounter).ColumnName + mstrFormulaColSuffix)
                        End If
                        If ldtData.Columns.Contains(ldtData.Columns(lintColCounter).ColumnName + mstrSourceDateColSuffix) Then
                            ldtData.Columns.Remove(ldtData.Columns(lintColCounter).ColumnName + mstrSourceDateColSuffix)
                        End If
                        If ldtData.Columns.Contains(mstrSOFColPrefix + ldtData.Columns(lintColCounter).ColumnName) Then
                            ldtData.Columns.Remove(mstrSOFColPrefix + ldtData.Columns(lintColCounter).ColumnName)
                        End If
                        ldtData.Columns.Remove(ldtData.Columns(lintColCounter).ColumnName)
                    End If
                    lintColCounter -= 1
                End While

                lstSnapshotMissingDataSources = New List(Of String)
                'If being loaded from Snapshot, Add the new data sources of current project that don't exist in the snapshot
                lintRowCounter = mstCurrentDataSources.Count - 1
                While lintRowCounter >= 0
                    If ldtData.Columns.Contains(mstCurrentDataSources.Item(lintRowCounter).SourceName) = False Then
                        lstSnapshotMissingDataSources.Add(mstCurrentDataSources.Item(lintRowCounter).SourceName)
                        AddNewColumn(mstCurrentDataSources.Item(lintRowCounter), ldtData, RecallChangesCaller.OnLoad)
                    End If
                    lintRowCounter -= 1
                End While

                'To set the ordinal of data source columns which are behind Activist column at the moment
                If ldtData.Columns("Region").Ordinal <> ldtData.Columns.Count - 1 Then
                    lintActivistColIndex = ldtData.Columns("Activist").Ordinal
                    lintColCounter = ldtData.Columns.Count - 1
                    While lintColCounter >= lintActivistColIndex
                        If mstAllDataSourceNameCols.Contains(ldtData.Columns(lintColCounter).ColumnName) Then
                            ldtData.Columns(ldtData.Columns(lintColCounter).ColumnName).SetOrdinal(lintActivistColIndex)
                            lintColCounter = ldtData.Columns.Count - 1
                            lintActivistColIndex = ldtData.Columns("Activist").Ordinal
                        Else
                            lintColCounter -= 1
                        End If
                    End While
                End If
            End If

            ''Add the previous data sources and their date columns in a list which will be marked hidden
            For Each lobjPreviousDataSources As PreviousDataSources In mstPreviousDataSources
                If ldtData.Columns.Contains(lobjPreviousDataSources.SourceName) Then
                    mstSysColumns.Add(lobjPreviousDataSources.SourceName)
                End If
            Next

            mstExcludedFromChooser = New List(Of String)
            'Hide all the system columns; also exclude them from the column chooser
            For Each lstrColName As String In mstSysColumns
                mstExcludedFromChooser.Add(lstrColName)
            Next

            grdData.DisplayLayout.Override.ExpansionIndicator = ShowExpansionIndicator.Never
            grdData.DisplayLayout.MaxBandDepth = 1

            'If it's being loaded from database and triggered by user, then remove the appearances as they will be created again.
            If penmDELoadUpType = DELoadUpType.CallDatabase Then
                Dim lintAppearanceCounter As Integer = grdData.DisplayLayout.Appearances.Count - 1
                While lintAppearanceCounter >= 0
                    grdData.DisplayLayout.Appearances.RemoveAt(lintAppearanceCounter)
                    lintAppearanceCounter -= 1
                End While
            End If

            If menmScreenType = DataHubScreenType.FinalizeList Then
                AddRemoveFLColumns(ldtData)
                ''To set the date column as adjancent to it's parent column in the datatable, when data is fetched from database parent column and associated date column are not adjacent
                SetGridDataFLColumnIndex(ldtData)
                SetParentGroupValues(ldtData, lblnCanReCalculate)
                mclsDataHubManager.FormatDuplicatedRecords(mintProjectID, mstrPreviousProjectName, ldtData)
            ElseIf menmScreenType = DataHubScreenType.DataEntry Then
                ''To set the date column as adjancent to it's parent column in the datatable, when data is fetched from database parent column and associated date column are not adjacent
                SetGridDataColumnIndex(ldtData)
            End If

            ''Get the index of some static columns in class level variable so that it can be used afterwards
            GetGridColumnIndex(ldtData)
            'Assign the data to the grid
            grdData.DataSource = ldtData
            Dim lintRowCount As Integer = ldtData.Rows.Count

            If ldtData.Rows(lintRowCount - 1)("Name") Is DBNull.Value Then
                ldtData.Rows.Remove(ldtData.Rows(lintRowCount - 1))
            End If

            'Add the previous project's 4th latest onwards columns in a list which will be marked hidden
            lintPreviousProjectCounter = 0
            Dim lintLastTraversedProjectID As Int16 = 0
            mstPreviousProjects.Reverse()
            For Each lobjPreviousProjects As PreviousProjects In mstPreviousProjects
                If lintLastTraversedProjectID <> lobjPreviousProjects.ProjectID Then
                    lintPreviousProjectCounter += 1
                End If
                If lintPreviousProjectCounter > 3 Then
                    grdData.Rows.Band.Columns(lobjPreviousProjects.DeliveryListing).Hidden = True
                End If
                lintLastTraversedProjectID = lobjPreviousProjects.ProjectID
            Next
            mstPreviousProjects.Reverse()

            'If a data source has even a single doubt, then mark the forecolor of that column in RED
            For Each lobjCurrentDataSources As CurrentDataSources In mstCurrentDataSources
                If lobjCurrentDataSources.HasAnyDoubts = True Then
                    grdData.Rows.Band.Columns(lobjCurrentDataSources.SourceName).Header.Appearance.BackColor = grdData.DisplayLayout.Appearances("RedBackColor").BackColor
                    'Else
                    '    grdData.Rows.Band.Columns(lobjCurrentDataSources.SourceName).Header.Appearance.BackColor = grdData.DisplayLayout.Appearances("ColHeadBackColor").BackColor
                End If
                ''Hide the SOF column of current data souce

                If lobjCurrentDataSources.IsND Or lobjCurrentDataSources.IsNIL Then
                    SetAppereanceHeader(lobjCurrentDataSources.SourceName)
                End If
            Next
            grdData.Rows.Band.Columns("Notes").Width = 26
            grdData.Rows.Band.Columns("Origin").Width = 38

            'Fixed the column headers
            grdData.DisplayLayout.Bands(0).Columns("Notes").Header.Fixed = True
            grdData.DisplayLayout.Bands(0).Columns("Origin").Header.Fixed = True
            grdData.DisplayLayout.Bands(0).Columns("InvestorName").Header.Fixed = True
            grdData.DisplayLayout.Bands(0).Columns("Name").Header.Fixed = True
            'Set the grid properites
            SetGridProperties()

            ''If there is any Previous project then the default sort order will be on the most recent previous project's Positions
            'If mstPreviousProjects.Count > 0 Then
            '    menmSortingOn = SortingOn.Positions
            '    mblnAnyChangesInLastProject = True
            '    ConductSorting(mstrDeliveryListingToSort)
            '    'To enable the sorting capabilities of FL's sortable position column of previous project(s) so that sorting with Desc Positions can be conducted.
            '    'grdData.DisplayLayout.Bands(0).Columns(mstrDeliveryListingToSort).SortComparer = New NumericComparer
            'Else
            '    'Otherwise set it to Ascending Order
            '    menmSortingOn = SortingOn.Ascending
            'End If

            grdData.BeginUpdate()
            grdData.SuspendRowSynchronization()
            ConductRecallDataChanges(mstCurrentDataSources, lstSnapshotMissingDataSources, True, ldtData, RecallChangesCaller.OnLoad)
            If menmDELoadUpType = DELoadUpType.Snapshot Then
                ConductSorting("")
            End If

            ' ''To set the date column as adjancent to it's parent column in the datatable, when data is fetched from database parent column and associated date column are not adjacent
            'SetGridDataColumnIndex(ldtData)

            ''Get the index of some static columns in class level variable so that it can be used afterwards
            'GetGridColumnIndex(ldtData)

            lintRowCounter = 0
            If menmDELoadUpType = DELoadUpType.Snapshot Then
                ' ''Operations that are to be performed on each row before binding the source with the grid
                For Each lRow As DataRow In ldtData.Rows
                    'If lRow.Item("InvestorName").ToString.StartsWith("A.H.W.") Then
                    '    lRow.Item(mintFundNameColIndex) = lRow.Item(mintFundNameColIndex)
                    'End If
                    If lRow.Item(mintLinkIDColIndex) = 0 Then
                        lRow.Item(mintFundNameColIndex) = ""
                    Else
                        lRow.Item(mintNameColIndex) = mstrFundPrefixSpaces + lRow.Item(mintNameColIndex).ToString.Trim
                        'e.Row.Appearance.BackColor = grdData.DisplayLayout.Appearances("FundRowBackColor").BackColor
                    End If
                    lintRowCounter += 1
                Next

                ''To set the ND value, the list contains the records who have ND value
                For Each lobjDEBasicSource As DEBasicSource In lstDEBasicSource
                    ldrNDRow = ldtData.Rows.Find(New Object() {lobjDEBasicSource.InvestorID, lobjDEBasicSource.FundID})
                    If ldrNDRow IsNot Nothing Then
                        ldrNDRow(lobjDEBasicSource.SourceName) = mstrNDValue
                    End If
                Next
                lstrSearch = New StringBuilder
                For Each lstrResearchCol As String In mstResearchSourceCols
                    If lstrResearchCol.Length > 0 Then
                        lstrSearch.Append("[" + lstrResearchCol + "] <> '' AND ")
                    End If
                Next
                If lstrSearch.Length > 0 Then
                    lstrSearch.Length = lstrSearch.Length - 4
                    ldrSearchedRows = ldtData.Select(lstrSearch.ToString)
                    For Each lRow As DataRow In ldrSearchedRows
                        For Each lstrResearchCol As String In mstResearchSourceCols
                            If lRow.Item(lstrResearchCol).ToString <> String.Empty Then
                                If ValidatewebsiteAddress(lRow.Item(lstrResearchCol)) Then
                                    lintRowCounter = ldtData.Rows.IndexOf(lRow)
                                    grdData.Rows(lintRowCounter).Cells(lstrResearchCol).Style = ColumnStyle.URL
                                End If
                            End If
                        Next
                    Next
                End If
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            lblDataLoading.Visible = False
            Me.Cursor = Cursors.Default
            lstSnapshotMissingDataSources = Nothing
            ldtData = Nothing
            grdData.ResumeRowSynchronization()
            grdData.EndUpdate()
            grdData.EventManager.SetEnabled(Infragistics.Win.UltraWinGrid.GridEventIds.AfterCellUpdate, True)
            lstSnapshotMissingDataSources = Nothing
            ldrSearchedRows = Nothing
            lstrSearch = Nothing
            ldrNDRow = Nothing
            lstDEBasicSource = Nothing
            lstResearchSources = Nothing
            grdData.UpdateData()
            ManageScreenStatus(0, mintProjectID, CommonCLL.UserID, False, True, False)
        End Try
    End Sub

    ''' <summary>
    ''' To add FL related columns
    ''' </summary>
    ''' <param name="ldtData"></param>
    ''' <remarks></remarks>
    Private Sub AddRemoveFLColumns(ByRef ldtData As DataTable)
        Dim lblnHasUpdates As Boolean = False
        Dim lblnHasDDInfo As Boolean = False
        Dim lblnHasRegister As Boolean = False
        Dim lblnHasBanklist As Boolean = False
        'Dim lblnHasPrimeBroker As Boolean = False
        Dim lobjCurrentDataSource As CurrentDataSources = Nothing
        Dim lintTraversingListingID As Integer

        For Each lobjListingInformation As ListingInformation In mstListingInformation
            lblnHasUpdates = False
            lblnHasDDInfo = False
            lblnHasRegister = False
            lblnHasBanklist = False
            'lblnHasPrimeBroker = False
            lintTraversingListingID = lobjListingInformation.ListingID
            lobjCurrentDataSource = mstCurrentDataSources.Find(Function(p) p.SourceTypeCode = SourceTypeCode.UPD.ToString AndAlso p.ListingID = lintTraversingListingID)
            If lobjCurrentDataSource IsNot Nothing Then
                lblnHasUpdates = True
            End If
            lobjCurrentDataSource = mstCurrentDataSources.Find(Function(p) (p.ESourceCode = DataSourceCode.DDCLEML.ToString OrElse _
                                                                                                   p.ESourceCode = DataSourceCode.DDQUEST.ToString) _
                                                                                                AndAlso p.ListingID = lintTraversingListingID)
            If lobjCurrentDataSource IsNot Nothing Then
                lblnHasDDInfo = True
            End If
            lobjCurrentDataSource = mstCurrentDataSources.Find(Function(p) (p.SourceTypeCode = SourceTypeCode.REG.ToString OrElse _
                                                                            p.SourceTypeCode = SourceTypeCode.RGT.ToString) AndAlso p.ListingID = lintTraversingListingID)
            If lobjCurrentDataSource IsNot Nothing Then
                lblnHasRegister = True
            End If
            lobjCurrentDataSource = mstCurrentDataSources.Find(Function(p) (p.SourceTypeCode = SourceTypeCode.BKL.ToString OrElse _
                                                                            p.SourceTypeCode = SourceTypeCode.EBL.ToString OrElse _
                                                                            p.SourceTypeCode = SourceTypeCode.PRB.ToString OrElse _
                                                                            p.SourceTypeCode = SourceTypeCode.EPB.ToString) AndAlso p.ListingID = lintTraversingListingID)
            If lobjCurrentDataSource IsNot Nothing Then
                lblnHasBanklist = True
            End If

            'If ldtData.Columns.Contains(mstrSOFColPrefix + mstrCurrentListingColPrefix + lobjListingInformation.ListingName) = False Then
            '    ldtData.Columns.Add(mstrSOFColPrefix + mstrCurrentListingColPrefix + lobjListingInformation.ListingName, GetType(Boolean))
            'End If

            'If ldtData.Columns.Contains(mstrCurrentListingColPrefix + lobjListingInformation.ListingName + mstrFormulaColSuffix) = False Then
            '    ldtData.Columns.Add(mstrCurrentListingColPrefix + lobjListingInformation.ListingName + mstrFormulaColSuffix, GetType(String))
            'End If

            If ldtData.Columns.Contains(mstrCurrentListingColPrefix + lobjListingInformation.ListingName) = False Then
                ldtData.Columns.Add(mstrCurrentListingColPrefix + lobjListingInformation.ListingName, GetType(String))
            End If

            ' Set shortcut for the Current listing column.
            If mdicShortCut Is Nothing Then
                mdicShortCut = New Dictionary(Of String, String)
                mdicShortCut.Add(mstrCurrentListingColPrefix + lobjListingInformation.ListingName, mstrCurrrentShortcut)
            Else
                If Not mdicShortCut.ContainsKey(mstrCurrentListingColPrefix + lobjListingInformation.ListingName) Then
                    mdicShortCut.Add(mstrCurrentListingColPrefix + lobjListingInformation.ListingName, mstrCurrrentShortcut)
                End If
            End If

            If ldtData.Columns.Contains(mstrSuggestedFinalListingColPrefix + lobjListingInformation.ListingName) = False Then
                ldtData.Columns.Add(mstrSuggestedFinalListingColPrefix + lobjListingInformation.ListingName, GetType(String))
            End If

            ' Set shortcut for the Suggested Final listing column.
            If mdicShortCut Is Nothing Then
                mdicShortCut = New Dictionary(Of String, String)
                mdicShortCut.Add(mstrSuggestedFinalListingColPrefix + lobjListingInformation.ListingName, mstrSuggestedShortcut)
            Else
                If Not mdicShortCut.ContainsKey(mstrSuggestedFinalListingColPrefix + lobjListingInformation.ListingName) Then
                    mdicShortCut.Add(mstrSuggestedFinalListingColPrefix + lobjListingInformation.ListingName, mstrSuggestedShortcut)
                End If
            End If

            If ldtData.Columns.Contains(mstrUpdatesColPrefix + lobjListingInformation.ListingName) = False AndAlso lblnHasUpdates Then
                ldtData.Columns.Add(mstrUpdatesColPrefix + lobjListingInformation.ListingName, GetType(String))
                ldtData.Columns.Add(mstrUpdatesColPrefix + lobjListingInformation.ListingName + mstrSourceDateColSuffix, GetType(String))
            ElseIf ldtData.Columns.Contains(mstrUpdatesColPrefix + lobjListingInformation.ListingName) AndAlso lblnHasUpdates = False Then
                ldtData.Columns.Remove(mstrUpdatesColPrefix + lobjListingInformation.ListingName)
                ldtData.Columns.Remove(mstrUpdatesColPrefix + lobjListingInformation.ListingName + mstrSourceDateColSuffix)
            End If
            If ldtData.Columns.Contains(mstrDDInfoColPrefix + lobjListingInformation.ListingName) = False AndAlso lblnHasDDInfo Then
                ldtData.Columns.Add(mstrDDInfoColPrefix + lobjListingInformation.ListingName, GetType(String))
                ldtData.Columns.Add(mstrDDInfoColPrefix + lobjListingInformation.ListingName + mstrSourceDateColSuffix, GetType(String))
            ElseIf ldtData.Columns.Contains(mstrDDInfoColPrefix + lobjListingInformation.ListingName) AndAlso lblnHasDDInfo = False Then
                ldtData.Columns.Remove(mstrDDInfoColPrefix + lobjListingInformation.ListingName)
                ldtData.Columns.Remove(mstrDDInfoColPrefix + lobjListingInformation.ListingName + mstrSourceDateColSuffix)
            End If
            If ldtData.Columns.Contains(mstrRegisterColPrefix + lobjListingInformation.ListingName) = False AndAlso lblnHasRegister Then
                ldtData.Columns.Add(mstrRegisterColPrefix + lobjListingInformation.ListingName, GetType(String))
            ElseIf ldtData.Columns.Contains(mstrRegisterColPrefix + lobjListingInformation.ListingName) AndAlso lblnHasRegister = False Then
                ldtData.Columns.Remove(mstrRegisterColPrefix + lobjListingInformation.ListingName)
            End If
            If ldtData.Columns.Contains(mstrBanklistColPrefix + lobjListingInformation.ListingName) = False AndAlso lblnHasBanklist Then
                ldtData.Columns.Add(mstrBanklistColPrefix + lobjListingInformation.ListingName, GetType(String))
            ElseIf ldtData.Columns.Contains(mstrBanklistColPrefix + lobjListingInformation.ListingName) AndAlso lblnHasBanklist = False Then
                ldtData.Columns.Remove(mstrBanklistColPrefix + lobjListingInformation.ListingName)
            End If
        Next
    End Sub

    Private Sub RemoveParentDataGroupColumns(ByRef ldtData As DataTable)

    End Sub

    ''' <summary>
    ''' To load the notes
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub LoadNotes()
        Dim lintDEProjectID As Integer
        Dim lintInvestorID As Integer
        Dim lintLinkID As Integer
        Dim lstNotes As IList(Of CrystalDataHub.BLL.DataHub.BusinessObject.Notes) = Nothing
        If rdbDECurrentNotes.Checked Then
            lintDEProjectID = mintProjectID
        Else
            lintDEProjectID = mintPreviousProjectID
        End If
        Dim lintFLProjectID As Integer
        If rdbFLCurrentNotes.Checked Then
            lintFLProjectID = mintProjectID
        Else
            lintFLProjectID = mintPreviousProjectID
        End If
        'lstNotes = New List(Of Notes)
        If grdData.ActiveRow Is Nothing Then Exit Sub
        If grdData.ActiveRow.GetCellValue("InvestorID") Is DBNull.Value Then Exit Sub
        lintInvestorID = grdData.ActiveRow.GetCellValue("InvestorID")
        Try
            'Fetch the notes corresponding to the current InvestorID and LinkID
            lintLinkID = IIf(grdData.ActiveRow.GetCellValue("LinkID") Is DBNull.Value, 0, grdData.ActiveRow.GetCellValue("LinkID"))
            lstNotes = mclsDataHubManager.GetNotes(lintDEProjectID, lintFLProjectID, lintInvestorID, lintLinkID)

            'If nothing is there, then set the default text in DE notes
            If lstNotes.Item(0).DENotes.Equals("") Then
                txtDENotes.Text = mstrDENotesDefaultText
            Else
                If lstNotes.Item(0).DENotes.StartsWith(mstrDENotesDefaultText) = False Then
                    lstNotes.Item(0).DENotes = mstrDENotesDefaultText.Trim + lstNotes.Item(0).DENotes
                End If
                txtDENotes.Text = lstNotes.Item(0).DENotes
            End If

            'If nothing is there, then set the default text in FL notes
            If lstNotes.Item(0).FLNotes.ToString.Equals("") Then
                txtFLNotes.Text = mstrFLNotesDefaultText
            Else
                If lstNotes.Item(0).FLNotes.StartsWith(mstrFLNotesDefaultText) = False Then
                    lstNotes.Item(0).FLNotes = mstrFLNotesDefaultText.Trim + lstNotes.Item(0).FLNotes
                End If
                txtFLNotes.Text = lstNotes.Item(0).FLNotes
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            'IDR = Nothing
            lstNotes = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' To save the data in the database
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub SaveData(ByRef pblnCanGoAhead As Boolean, ByVal pblnShowMessage As Boolean)
        'If there is nothing to save, then exit
        If mstDataSourceChanges.Count = 0 AndAlso mstPreviousProjectChanges.Count = 0 AndAlso mstLinkingChanges.Count = 0 Then Exit Sub
        Dim lstEntityIDs As New List(Of Integer)
        Dim lserDataChanges As New System.Xml.Serialization.XmlSerializer(GetType(List(Of DataSourceChanges)))
        Dim lserPreviousProjectChanges As New System.Xml.Serialization.XmlSerializer(GetType(List(Of FLPositionChanges)))
        Dim lserLinkingChanges As New System.Xml.Serialization.XmlSerializer(GetType(List(Of LinkingChanges)))
        Dim enmResult As DBResult
        Dim lstrErrorMessage As String = ""
        Dim lobjDateSupported As List(Of CurrentDataSources) = Nothing
        Dim lstLinkingDetails As List(Of LinkingDetails) = Nothing
        Dim lobjLinkingDetails As LinkingDetails = Nothing
        Dim ldrNewProjectDBRow As DataRow = Nothing
        Dim ldtCurrentData As DataTable = Nothing
        Dim lblnIsFromFL As Boolean
        Try
            If menmScreenType = DataHubScreenType.FinalizeList Then
                lblnIsFromFL = True
            Else
                lblnIsFromFL = False
            End If

            '''''Starts: Sukhminder - 22nd Sep, 2012 - Commented as Mandatory date is not working properly. As per discussions, for the moment remove the validation, user'll
            '''''take care of mandatory date himself

            ''Formulate the array which contains the list of date supported data sources
            'lobjDateSupported = mstCurrentDataSources.FindAll(Function(p) p.AccessStatus = SourceAccessbility.Locked.ToString AndAlso _
            '                                     (p.SourceTypeCode = SourceTypeCode.UPD.ToString OrElse p.SourceTypeCode = SourceTypeCode.RSH.ToString OrElse _
            '                                      p.ESourceCode = DataSourceCode.DDCLEML.ToString OrElse _
            '                                                                                   p.ESourceCode = DataSourceCode.DDQUEST.ToString))
            ''mstCurrentDataSources.Select(Function(p) p.AccessStatus=SourceAccessbility.Locked.ToString andalso (lobjCurrentDataSources.SourceTypeCode = SourceTypeCode.RSH.ToString OrElse)
            'For Each lobjCurrentDataSources As CurrentDataSources In lobjDateSupported
            '    lstEntityIDs.Add(lobjCurrentDataSources.EntityID)
            'Next

            ''Check if the date is specified for all such date supported data sources, if not inform the user
            'For Each lobjDataSourceChanges As DataSourceChanges In mstDataSourceChanges
            '    If lstEntityIDs.Contains(lobjDataSourceChanges.EntityID) AndAlso lobjDataSourceChanges.SourceDate Is Nothing AndAlso (lobjDataSourceChanges.Position <> 0 OrElse lobjDataSourceChanges.Position IsNot Nothing) Then
            '        pblnCanGoAhead = False
            '        ShowMessageBox(DBResult.DH_DDINFO_MNDTRY_DATE)
            '        Exit Sub
            '    End If
            'Next
            '''''Ends: Sukhminder - 22nd Sep, 2012 - Commented as Mandatory date is not working properly. As per discussions, for the moment remove the validation, user'll
            '''''take care of mandatory date himself

            'Save data in the database
            mclsDataHubManager.ManageData(SerializeFromObject(lserDataChanges, System.Text.Encoding.UTF8, mstDataSourceChanges), _
                                          SerializeFromObject(lserPreviousProjectChanges, System.Text.Encoding.UTF8, mstPreviousProjectChanges), _
                                          SerializeFromObject(lserLinkingChanges, System.Text.Encoding.UTF8, mstLinkingChanges), _
                                          mintProjectID, enmResult, lstrErrorMessage, lstLinkingDetails, IIf(menmScreenType = DataHubScreenType.DataEntry, True, False))
            If enmResult = DBResult.SUCCESS Then
                grdData.ClearUndoHistory()
                If lstLinkingDetails IsNot Nothing Then
                    If lstLinkingDetails.Count > 0 Then
                        ldtCurrentData = grdData.DataSource
                        For Each lobjLinkingDetails In lstLinkingDetails
                            ldrNewProjectDBRow = ldtCurrentData.Rows.Find(New Object() {lobjLinkingDetails.InvestorID, lobjLinkingDetails.FundID})
                            ldrNewProjectDBRow.Item("LinkID") = lobjLinkingDetails.LinkID
                        Next
                        ldtCurrentData.AcceptChanges()
                    End If
                End If
                If pblnShowMessage Then
                    MessageBox.Show("Data updated successfully.", CommonCLL.mstrMsgBoxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information)
                End If
                'mdtPreviousProjectChanges.Clear()
            ElseIf enmResult = DBResult.FAILED Then
                Me.ShowMessageBox(DBResult.DH_DATA_SAVE_FAILED, lstrErrorMessage)
            Else
                Me.ShowMessageBox(enmResult)
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            lobjDateSupported = Nothing
            lserDataChanges = Nothing
            lserPreviousProjectChanges = Nothing
            lserLinkingChanges = Nothing
            lobjLinkingDetails = Nothing
            lstLinkingDetails = Nothing
            ldrNewProjectDBRow = Nothing
            ldtCurrentData = Nothing
            If pblnCanGoAhead Then
                'Clear the tracking tables
                mstDataSourceChanges = New List(Of DataSourceChanges)
                mstPreviousProjectChanges = New List(Of FLPositionChanges)
                mstLinkingChanges = New List(Of LinkingChanges)
            End If
        End Try
    End Sub

    Private Sub SaveDataInText()
        Dim lstrData As StringBuilder = New StringBuilder
        Dim rootband As UltraGridBand = grdData.Rows.Band
        Dim lColCounter As Integer = rootband.Columns.Count
        Dim objStreamWriter As StreamWriter
        Try
            For Each lCol As UltraGridColumn In rootband.Columns
                lstrData.Append(lCol.Header.Caption)
                lstrData.Append(If(lCol.Index = rootband.Columns.Count - 1, Environment.NewLine, ","))
            Next
            For Each lrow As UltraGridRow In grdData.Rows
                lColCounter = 0
                While lColCounter < rootband.Columns.Count
                    lstrData.Append(lrow.GetCellValue(rootband.Columns(lColCounter)))
                    lstrData.Append(If(lColCounter = rootband.Columns.Count - 1, Environment.NewLine, ","))
                    lColCounter += 1
                End While
            Next
            objStreamWriter = New StreamWriter("D:\output.txt", True, Encoding.Unicode)
            objStreamWriter.WriteLine(lstrData.ToString)
            objStreamWriter.Close()
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            lstrData = Nothing
            rootband = Nothing
            objStreamWriter = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' To save the snapshot at the specified folder and details in the DB
    ''' </summary>
    ''' <remarks></remarks>
    Private Function SaveSnapshot() As Boolean
        'Return False
        Dim lstrOldFolderPath As String = ""
        Dim lstrHiddenColumns As String = ""
        Dim ExcWorkbook As Workbook = Nothing
        Dim lstrFileExtention As String = ".xls"
        Dim lwrbkFormat As WorkbookFormat = WorkbookFormat.Excel97To2003
        Dim lstrDateTime As String = DateTime.Now.ToString()
        Dim lstrFilePath As String
        Dim lobjws As Worksheet
        Try
            If grdData.Rows.Band.Columns.Count > 255 OrElse grdData.Rows.Count > 65535 Then
                lstrFileExtention = ".xlsx"
                lwrbkFormat = WorkbookFormat.Excel2007
            End If
            'Check If the folder path is invalid
            If mstrDESnapshotPath.Equals("") Then
                Me.ShowMessageBox(DBResult.FOLDER_NOTACCESS, BaseClass.Capitalize("Data Entry"))
                Return False
            End If

            'Formulate the name of the file being created
            lstrDateTime = lstrDateTime.Replace(":", "_").Replace("/", "_")
            'Get the already saved snapshot path, so that it can be removed
            lstrOldFolderPath = mclsDataHubManager.GetSnapshotFilePath(mintProjectID)
            lstrFilePath = mstrDESnapshotPath + "\" + mstrClientName + " - " + mstrProjectName + " - DE - " & " - " & lstrDateTime & lstrFileExtention
            'Save the file in 2003 format, as it's quicker to open through infragistics
            ExcWorkbook = New Workbook(lwrbkFormat, WorkbookPaletteMode.CustomPalette)
            lobjws = ExcWorkbook.Worksheets.Add(mstrProjectName)
            'Keep track of the hidden columns so that they can be set to hidden when the snapshot will be reloaded
            For Each lCol As UltraGridColumn In grdData.DisplayLayout.Bands(0).Columns
                If lCol.Hidden Then
                    lstrHiddenColumns += lCol.Header.Caption + "~"
                End If
            Next

            'Unhide the rows so that all rows can be saved in the snapshot
            For Each lRow As UltraGridRow In grdData.Rows
                If lRow.Hidden Then
                    lRow.Hidden = False
                End If
            Next
            lstrHiddenColumns.TrimEnd("~")
            UltraGridExcelExporter1.FileLimitBehaviour = FileLimitBehaviour.ThrowException
            '' ''Export the grid data into excel file
            UltraGridExcelExporter1.Export(grdData, lobjws, 0, 0)
            ' ''Save the excel file
            ExcWorkbook.Save(lstrFilePath)
            ''Updates the statues in the database
            ''''''''''''''Starts:As the snapshot is created and contains all the latest data, hence remove the track of data changes for the given project
            mclsDataHubManager.InsertUpdateSnapshot(mintProjectID, lstrFilePath, True, lstrHiddenColumns)
            ''''''''''''''Ends:As the snapshot is created and contains all the latest data, hence remove the track of data changes for the given project
            'Delete the old file
            If lstrOldFolderPath IsNot Nothing Then
                If lstrOldFolderPath.Equals("") = False AndAlso IO.File.Exists(lstrOldFolderPath) Then
                    System.IO.File.Delete(lstrOldFolderPath)
                End If
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
            Return False
        Finally
            ExcWorkbook = Nothing
        End Try
        Return True
    End Function

    ''' <summary>
    ''' Save the notes in database
    ''' </summary>
    ''' <param name="pblnIsDENotes">Check if it's from DE or FL</param>
    ''' <remarks></remarks>
    Private Sub SaveNotes(ByVal pblnIsDENotes As Boolean)
        Dim enmResult As DBResult = DBResult.SUCCESS
        Dim lstrNotesTitle As String = "Notes"
        Dim lstrInvestorFundIDData As String
        Dim larrKeyCols() As String = {""}
        Dim larrExcludingCols() As String
        Dim lenmDENotesSaveType As NotesSaveType
        Dim lenmFLNotesSaveType As NotesSaveType
        Dim lstrDENotes As String
        Dim lstrFLNotes As String
        Dim lblnZeroIsSelectedRow As Boolean = False
        Dim lstrNotes As String = ""
        Dim lstrLockedBy As New StringBuilder
        Dim lblnHasAnyLockedCol As Boolean = False
        Dim lstNotesStatus As IList(Of NotesStatus) = Nothing

        Dim lintUserNameTextLength As Integer '= ("- " + CommonCLL.UserFullName + ":").Length
        Dim lstrEnteredText As String
        Dim lintCompareResults As Int16
        Try
            For Each lobjCurrentDataSources As CurrentDataSources In mstCurrentDataSources
                If lobjCurrentDataSources.AccessStatus = SourceAccessbility.Locked.ToString Then
                    lblnHasAnyLockedCol = True
                    If lobjCurrentDataSources.SourceTypeCode = SourceTypeCode.UPD.ToString Then
                        lstrLockedBy.Append(lobjCurrentDataSources.SourceName.Substring(0, lobjCurrentDataSources.SourceName.Length - lobjCurrentDataSources.ListingName.Length).Trim)
                        Exit For
                    Else
                        lstrLockedBy.Append(lobjCurrentDataSources.SourceName)
                    End If
                End If
            Next

            If lstrLockedBy.Length > 0 Then
                lstrLockedBy.Append(" - ")
            End If

            'Check whether to overwrite or append
            If pblnIsDENotes Then
                lenmDENotesSaveType = NotesSaveType.AsItIs
                lenmFLNotesSaveType = NotesSaveType.AsItIs
            Else
                lenmDENotesSaveType = NotesSaveType.AsItIs
                lenmFLNotesSaveType = NotesSaveType.AsItIs
            End If
            'Exclude columns which are not going to help in fetching notes information
            larrExcludingCols = GetExcludingColsForNotes()

            'If no row is selected, then make the active row as selected
            If grdData.Selected.Rows.Count = 0 Then
                lblnZeroIsSelectedRow = True
                grdData.Rows(grdData.ActiveRow.Index).Selected = True
            End If

            lstrInvestorFundIDData = CommonCLL.GetXMlFromUltraGrid(grdData, larrExcludingCols, larrKeyCols, False)
            If lblnZeroIsSelectedRow Then
                grdData.Rows(grdData.ActiveRow.Index).Selected = False
            End If

            lstrDENotes = txtDENotes.Text.Trim
            lstrFLNotes = txtFLNotes.Text.Trim
            lintUserNameTextLength = ("- " + CommonCLL.UserFullName + ":").Length

            'Dim lintNotePrefixLength As Int16
            'Dim lintDefaultLockedNotesText As String

            'Check if DE Notes text box contains any note actually
            If lstrDENotes.Length > lintUserNameTextLength Then
                If lblnHasAnyLockedCol Then
                    'mstrDENotesDefaultText
                    'lstrEnteredText = lstrDENotes.Substring(lstrDENotes.Length - lstrLockedBy.Length - lintUserNameTextLength, lintUserNameTextLength)
                    'lintCompareResults 
                    lstrEnteredText = mstrDENotesDefaultText + "- " + lstrLockedBy.ToString + CommonCLL.UserFullName + " :".Trim
                    lintCompareResults = String.Compare(lstrDENotes, lstrEnteredText)
                    If lintCompareResults = 0 Then
                        lstrDENotes = mstrDENotesDefaultText.Trim
                        'lstrDENotes = lstrDENotes.Substring(0, lstrDENotes.Length - lstrLockedBy.Length - lintUserNameTextLength)
                        'lstrDENotes = lstrDENotes.Trim
                    Else
                        If lstrDENotes.EndsWith("- " + lstrLockedBy.ToString + CommonCLL.UserFullName + " :".Trim) Then
                            lstrDENotes = lstrDENotes.Substring(0, lstrDENotes.Length - ("- " + lstrLockedBy.ToString + CommonCLL.UserFullName + " :".Trim).Length).Trim()
                        ElseIf lstrDENotes.EndsWith("- " + CommonCLL.UserFullName + " :".Trim) Then
                            lstrDENotes = lstrDENotes.Substring(0, lstrDENotes.Length - ("- " + CommonCLL.UserFullName + " :".Trim).Length).Trim()
                        End If
                        'lintDefaultLockedNotesText = "- " + lstrLockedBy.ToString + CommonCLL.UserFullName + " :".Trim
                        'lintNotePrefixLength = ("- " + lstrLockedBy.ToString + CommonCLL.UserFullName + " :".Trim).Length
                        'If String.Compare(lstrDENotes.Substring(lstrDENotes.Length - lintNotePrefixLength), lintDefaultLockedNotesText) = 0 Then
                        '    lstrDENotes = lstrDENotes.Substring(0, lstrDENotes.Length - lintNotePrefixLength).Trim
                        'End If
                    End If
                Else
                    lstrEnteredText = mstrDENotesDefaultText + "- " + CommonCLL.UserFullName + " :".Trim
                    If String.Compare(lstrDENotes, lstrEnteredText) = 0 Then
                        lstrDENotes = mstrDENotesDefaultText.Trim
                        'lstrDENotes = lstrDENotes.Substring(0, lstrDENotes.Length - lstrLockedBy.Length - lintUserNameTextLength)
                        'lstrDENotes = lstrDENotes.Trim
                    End If
                End If
            End If

            'Check if FL Notes text box contains any note actually
            If lstrFLNotes.Length > lintUserNameTextLength Then
                lstrEnteredText = mstrFLNotesDefaultText + "- " + CommonCLL.UserFullName + " :".Trim
                If String.Compare(lstrFLNotes, lstrEnteredText) = 0 Then
                    lstrFLNotes = mstrFLNotesDefaultText.Trim
                End If
                'If String.Compare(("- " + CommonCLL.UserFullName + ":"), lstrFLNotes.Substring(lstrFLNotes.Length - lintUserNameTextLength, lintUserNameTextLength)) = 0 Then
                '    lstrFLNotes = lstrFLNotes.Substring(0, lstrFLNotes.Length - lintUserNameTextLength)
                '    lstrFLNotes = lstrFLNotes.Trim
                'End If
            End If

            'If it contains only the default value, then set it to Blank
            If lstrDENotes.Equals("") OrElse lstrDENotes.Equals(mstrDENotesDefaultText.Trim) OrElse lstrDENotes.Equals(mstrDENotesDefaultText + "- " + CommonCLL.UserFullName + ":") Then
                lstrDENotes = ""
            End If
            'If it contains only the default value, then set it to Blank
            If lstrFLNotes.Equals("") OrElse lstrFLNotes.Equals(mstrFLNotesDefaultText.Trim) OrElse lstrFLNotes.Equals(mstrFLNotesDefaultText + "- " + CommonCLL.UserFullName + ":") Then
                lstrFLNotes = ""
            End If
            'If lstrDENotes.Equals("") AndAlso lstrFLNotes.Equals("") Then Exit Sub
            'Save the data in the database
            lstNotesStatus = mclsDataHubManager.ManageNotes(mintProjectID, lstrInvestorFundIDData, lstrDENotes, lstrFLNotes, CommonCLL.UserID, enmResult, lenmDENotesSaveType, lenmFLNotesSaveType, grdData.ActiveRow.GetCellValue("InvestorID"), IIf(grdData.ActiveRow.GetCellValue("LinkID") Is DBNull.Value, 0, grdData.ActiveRow.GetCellValue("LinkID")), lstrNotes)
            If enmResult = DBResult.FAILED Then
                Me.ShowMessageBox(DBResult.FAILED, lstrNotesTitle)
            ElseIf enmResult = DBResult.EXIST Then
                Me.ShowMessageBox(DBResult.EXIST, lstrNotesTitle)
            ElseIf enmResult = DBResult.SUCCESS Then
                'grdData.ActiveRow.Cells("Notes").Value = lstrNotes
                UpdateNotesStatus(lstNotesStatus)
            End If
            'txtDENotes.Text = lstrDENotes
            'txtFLNotes.Text = lstrFLNotes
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            lenmDENotesSaveType = Nothing
            lenmFLNotesSaveType = Nothing
            lstrLockedBy = Nothing
            lstNotesStatus = Nothing
        End Try
    End Sub

    Private Sub UpdateNotesStatus(ByVal lstNotesStatus As IList(Of NotesStatus))
        Dim ldtCurrentData As DataTable
        Dim ldrNotesRow As DataRow = Nothing
        Try
            If lstNotesStatus.Count > 0 Then
                ldtCurrentData = grdData.DataSource
                grdData.SuspendRowSynchronization()
                For Each lobjNotesStatus As NotesStatus In lstNotesStatus
                    ldrNotesRow = ldtCurrentData.Rows.Find(New Object() {lobjNotesStatus.InvestorID, lobjNotesStatus.FundID})
                    If ldrNotesRow IsNot Nothing Then
                        ldrNotesRow("Notes") = lobjNotesStatus.Notes
                    End If
                Next
                grdData.ResumeRowSynchronization()
                grdData.UpdateData()
                ldtCurrentData = Nothing
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            ldtCurrentData = Nothing
            ldrNotesRow = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' Exclude columns which are not going to be used in helping fetching Notes data
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function GetExcludingColsForNotes() As String()
        Dim lColBand As UltraGridBand = grdData.Rows.Band
        Dim lintColCount As Int16 = 0
        Dim lintArrColCount As Int16 = 0
        Dim larrExcludingCols(1) As String
        Try
            'Exclude columns/values that are not going to be used in insert process
            While lintColCount < lColBand.Columns.Count
                If lColBand.Columns(lintColCount).Header.Caption.Equals("InvestorID") = False AndAlso lColBand.Columns(lintColCount).Header.Caption.Equals("LinkID") = False Then
                    larrExcludingCols(lintArrColCount) = lColBand.Columns(lintColCount).Header.Caption
                    ReDim Preserve larrExcludingCols(lintArrColCount + 1)
                    lintArrColCount += 1
                End If
                lintColCount += 1
            End While
            ReDim Preserve larrExcludingCols(lintArrColCount - 1)
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            lColBand = Nothing
        End Try
        Return larrExcludingCols
    End Function

    ''' To load the data from the text snapshot into datatable
    ''' </summary>
    ''' <param name="ldtData"></param>
    ''' <param name="lstrSnapshotPath"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Function LoadSnapshotFromText(ByRef ldtData As DataTable, ByVal lstrSnapshotPath As String) As System.Data.DataTable
        Dim lines As String() = Nothing
        Dim sArr As String() = Nothing
        Dim ldrSnapshotRow As DataRow
        Dim lintRowCounter As Integer = 0
        Dim myDataColumn As DataColumn
        Dim lstSOFColIndexes As New List(Of Integer)
        Dim lstSourceDateColIndexes As New List(Of Integer)
        Dim lstrDemiliter As Char = mdlDataHubBLLCommon.mstrSnapshotDemiliter
        Dim csv As CsvReader = Nothing
        Dim ldrData As IDataReader = Nothing
        Dim lstrColName As String
        Dim finalLine As String = ""
        Dim keyColumn(1) As DataColumn
        Try
            csv = New CsvReader(New StreamReader(lstrSnapshotPath), True, lstrDemiliter)
            csv.MissingFieldAction = MissingFieldAction.ReplaceByNull
            ldrData = csv
            If ldtData Is Nothing Then
                ldtData = New DataTable
            End If
            For i = 0 To ldrData.FieldCount - 1
                lstrColName = ldrData.GetName(i)
                'The export that was demonstrated earlier utilizes the first row
                'for the column header.  We can now use that to give column names.
                If New Object() {"InvestorID", "LinkID", "FundID", "ProjectID", "RowNumber", "DenseRank", "FundDenseRank"}.Contains(lstrColName) Then
                    myDataColumn = New DataColumn(lstrColName, GetType(Integer))
                ElseIf New Object() {"IsInvestor", "IsMasterDB", "IsManaged", "IsCutRow"}.Contains(lstrColName) Then
                    myDataColumn = New DataColumn(lstrColName, GetType(Boolean))
                ElseIf lstrColName.Equals("UserID") Then
                    myDataColumn = New DataColumn(lstrColName, GetType(Int16))
                ElseIf lstrColName.StartsWith(mstrSOFColPrefix) Then
                    myDataColumn = New DataColumn(lstrColName, GetType(Boolean))
                    myDataColumn.DefaultValue = True
                    lstSOFColIndexes.Add(ldtData.Columns.Count)
                ElseIf lstrColName.Equals("MInvestorTypeID") Then
                    myDataColumn = New DataColumn(lstrColName, GetType(Byte))
                ElseIf mstAllDataSourceDateCols.Contains(lstrColName) Then
                    myDataColumn = New DataColumn(lstrColName, GetType(Date))
                    'myDataColumn = New DataColumn(lstrColName, GetType(String))
                    lstSourceDateColIndexes.Add(ldtData.Columns.Count)
                Else
                    myDataColumn = New DataColumn(lstrColName)
                End If
                'myDataColumn = New DataColumn(lstrColName)
                ldtData.Columns.Add(myDataColumn)
            Next
            ldtData.Load(csv)
            ldrData.Close()
            ldrData.Dispose()

            keyColumn(0) = ldtData.Columns("InvestorID")
            keyColumn(1) = ldtData.Columns("FundID")

            ldtData.PrimaryKey = keyColumn
        Catch ex As Exception
            MessageBox.Show(ex.ToString, CommonCLL.mstrMsgBoxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
            Return Nothing
        Finally
            ldrData.Close()
            ldrData.Dispose()
            lstSOFColIndexes = Nothing
            lstSourceDateColIndexes = Nothing
            ldrSnapshotRow = Nothing
            lines = Nothing
            sArr = Nothing
            myDataColumn = Nothing
            keyColumn = Nothing
            ldrData = Nothing
        End Try
        Return ldtData
    End Function

    ''' <summary>
    ''' To save the snapshot at the specified folder and details in the DB
    ''' </summary>
    ''' <remarks></remarks>
    Private Function SaveSnapshotInText() As Boolean
        Dim lstrOldFolderPath As String = ""
        Dim lstrHiddenColumns As String = ""
        Dim lstSnapshotExcludingCols As List(Of Integer) = Nothing
        Dim lobjCurrentDataSource As CurrentDataSources = Nothing
        Dim ldtCurrentData As DataTable = Nothing
        Dim writer As TextWriter
        Dim lstrColName As String
        Dim lstrPositionColName As String
        Try
            'Check If the folder path is invalid
            If mstrDESnapshotPath.Equals("") Then
                Me.ShowMessageBox(DBResult.FOLDER_NOTACCESS, BaseClass.Capitalize("Data Entry"))
                Return False
            End If
            ldtCurrentData = grdData.DataSource
            ldtCurrentData.AcceptChanges()
            'Formulate the name of the file being created
            Dim lstrDateTime As String = DateTime.Now.ToString()
            lstrDateTime = DateTime.Now.ToString()
            lstrDateTime = lstrDateTime.Replace(":", "_").Replace("/", "_")
            'Get the already saved snapshot path, so that it can be removed
            lstrOldFolderPath = mclsDataHubManager.GetSnapshotFilePath(mintProjectID)
            Dim lstrFilePath As String = mstrDESnapshotPath + "\" + mstrClientName + " - " + mstrProjectName + " - DH - " & lstrDateTime & ".txt"

            'Keep track of the hidden columns so that they can be set to hidden when the snapshot will be reloaded
            For Each lCol As UltraGridColumn In grdData.DisplayLayout.Bands(0).Columns
                If lCol.Hidden Then
                    lstrHiddenColumns += lCol.Header.Caption + "~"
                End If
            Next
            lstrHiddenColumns.TrimEnd("~")
            Dim lintParentColIndex As Int16 = ldtCurrentData.Columns("Parent").Ordinal
            Dim lintActivistColIndex As Int16 = ldtCurrentData.Columns("Activist").Ordinal
            Dim lblnIsDeleteable As Boolean = False
            lstSnapshotExcludingCols = New List(Of Integer)
            Dim lintColCounter As Integer = mintParentIndex + 1
            ''To save some of the associated columns to be saved in the snapshot, see below the criteris for that.
            ''For Update - sof, formula, soure date, previous positions.
            ''For Research & Client Emails - Date & Source column need to be saved in the snapshot
            While lintColCounter < ldtCurrentData.Columns.Count
                lstrColName = ldtCurrentData.Columns(lintColCounter).ColumnName
                If mstAllDataSourceNameCols.Contains(lstrColName) = False _
                    AndAlso marrPreviousProjects.Contains(lstrColName) = False _
                    AndAlso mstAttributeSet2.Contains(lstrColName) = False _
                    AndAlso lstrColName.Contains(mstrClientSpecificSourceColSuffix) = False _
                    AndAlso lstrColName.Contains(mstrFilingDateColSuffix) = False _
                    AndAlso lstrColName.Contains(mstrGenericSourceColSuffix) = False _
                    AndAlso mstDataSourceParentGroupPositionCol.Contains(lstrColName) = False _
                    AndAlso mstDataSourceParentGroupDateCol.Contains(lstrColName) = False _
                    AndAlso lstrColName.StartsWith(mstrCurrentListingColPrefix) = False _
                    AndAlso lstrColName.StartsWith(mstrSuggestedFinalListingColPrefix) = False _
                    Then
                    If mstDataSourceParentGroupPositionCol.Contains(lstrColName) OrElse lstrColName.StartsWith(mstrCurrentListingColPrefix) OrElse lstrColName.StartsWith(mstrSuggestedFinalListingColPrefix) Then
                        lblnIsDeleteable = True
                    End If
                    lblnIsDeleteable = False
                    lstrPositionColName = ""
                    If marrPreviousDataSourceNameCols.Contains(lstrColName) Then
                        If mstPreviousDataSources.Find(Function(p) p.SourceName = lstrColName).SourceTypeCode <> SourceTypeCode.UPD.ToString Then
                            lblnIsDeleteable = True
                        End If
                    ElseIf lstrColName.StartsWith(mstrSOFColPrefix) Then
                        lblnIsDeleteable = True
                    ElseIf lstrColName.EndsWith(mstrFormulaColSuffix) Then
                        lblnIsDeleteable = True
                    ElseIf lstrColName.EndsWith(mstrSourceDateColSuffix) Then
                        lstrPositionColName = lstrColName.Substring(0, lstrColName.Length - mstrSourceDateColSuffix.Length)
                        If mstEditableDataSourceNameCols.Contains(lstrPositionColName) Then
                            lobjCurrentDataSource = mstCurrentDataSources.Find(Function(p) p.SourceName = lstrPositionColName)
                            If lobjCurrentDataSource.SourceTypeCode <> SourceTypeCode.UPD.ToString AndAlso lobjCurrentDataSource.SourceTypeCode <> SourceTypeCode.RSH.ToString _
                                AndAlso (lobjCurrentDataSource.SourceTypeCode <> SourceTypeCode.DDI.ToString AndAlso lobjCurrentDataSource.ESourceCode <> DataSourceCode.DDCLEML) Then
                                lblnIsDeleteable = True
                            End If
                        End If
                    ElseIf lstrColName.EndsWith(mstrSourceColSuffix) Then
                        lstrPositionColName = lstrColName.Substring(0, lstrColName.Length - mstrSourceColSuffix.Length)
                        If mstEditableDataSourceNameCols.Contains(lstrPositionColName) Then
                            lobjCurrentDataSource = mstCurrentDataSources.Find(Function(p) p.SourceName = lstrPositionColName)
                            If lobjCurrentDataSource.SourceTypeCode <> SourceTypeCode.RSH.ToString AndAlso lobjCurrentDataSource.SourceTypeCode <> SourceTypeCode.PBC.ToString Then
                                lblnIsDeleteable = True
                            End If
                        End If
                    End If
                    If lblnIsDeleteable Then
                        lstSnapshotExcludingCols.Add(ldtCurrentData.Columns(lintColCounter).Ordinal)
                    End If
                End If
                lintColCounter += 1
            End While

            lstSnapshotExcludingCols.Sort()
            Dim columnNames = ldtCurrentData.Columns.Cast(Of DataColumn)() _
                              .Where(Function(column) Not lstSnapshotExcludingCols.Contains(column.Ordinal)) _
                              .Select(Function(column) column.ColumnName).ToArray()
            writer = File.CreateText(lstrFilePath)
            writer.WriteLine(String.Join(mdlDataHubBLLCommon.mstrSnapshotDemiliter, columnNames))
            Dim lstrData As String
            For Each row As DataRow In ldtCurrentData.Rows
                lstrData = String.Join(mdlDataHubBLLCommon.mstrSnapshotDemiliter, row.ItemArray.Where(Function(value, index) Not lstSnapshotExcludingCols.Contains(index)))
                writer.WriteLine(String.Join(mdlDataHubBLLCommon.mstrSnapshotDemiliter, row.ItemArray.Where(Function(value, index) Not lstSnapshotExcludingCols.Contains(index))))
            Next
            writer.Close()
            ''Updates the statues in the database
            ''''''''''''''Starts:As the snapshot is created and contains all the latest data, hence remove the track of data changes for the given project
            mclsDataHubManager.InsertUpdateSnapshot(mintProjectID, lstrFilePath, True, lstrHiddenColumns)
            ''''''''''''''Ends:As the snapshot is created and contains all the latest data, hence remove the track of data changes for the given project
            'Delete the old file
            If lstrOldFolderPath IsNot Nothing Then
                If lstrOldFolderPath.Equals("") = False AndAlso IO.File.Exists(lstrOldFolderPath) Then
                    Dim lstrFileName As String = System.IO.Path.GetFileName(lstrOldFolderPath)
                    Dim lstrArchieveFilePath As String = mstrDESnapshotPathArchieve + "\" + lstrFileName
                    System.IO.File.Move(lstrOldFolderPath, lstrArchieveFilePath)
                    'System.IO.File.Delete(lstrOldFolderPath)
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString, CommonCLL.mstrMsgBoxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
            Return False
        Finally
            ldtCurrentData = Nothing
            writer = Nothing
            lstSnapshotExcludingCols = Nothing
            lobjCurrentDataSource = Nothing
        End Try
        Return True
    End Function

#End Region

#Region "Auto Save And Recall"
    ''' <summary>
    ''' To check if a Recall Data change is required, To hide/unhide the columns and to add the new columns for Add New column
    ''' </summary>
    ''' <param name="lstDataEntities">Data columns to be checked from</param>
    ''' <param name="pblnIsFromSnapshot">Is from Snapshot</param>
    ''' <param name="pdtCurrentData">Data columns to be checked</param>
    ''' <remarks></remarks>
    Private Sub ConductRecallDataChanges(ByVal lstDataEntities As List(Of CurrentDataSources), ByVal lstSnapshotMissingDataSources As List(Of String), ByVal pblnIsFromSnapshot As Boolean, ByRef pdtCurrentData As DataTable, _
                                         ByVal penmRecallChangesCaller As RecallChangesCaller)
        Dim lstrEntitiesIDsForDBRecall As StringBuilder = Nothing
        Dim lstrDataEntitiesForDBRecall As StringBuilder = Nothing
        Dim lblnCanGetDataFromDB As Boolean = False
        Dim lblnDoesColumnExists As Boolean = True
        Dim lblnShouldRecallUsed As Boolean = True
        Dim lobjLoadedDataSource As CurrentDataSources = Nothing
        Dim lblnShouldReSort As Boolean = False
        Dim lstActiveDataSources As New List(Of CurrentDataSources)
        Dim lblnCanCheckRecallCalling As Boolean = True
        Try
            'If it's from Snapshot and there is no user in the project's data entry screen, then there is no need to call Recall changes
            If pblnIsFromSnapshot Then
                If lstSnapshotMissingDataSources IsNot Nothing Then
                    If lstSnapshotMissingDataSources.Count > 0 Then
                        lblnCanCheckRecallCalling = False
                        lblnShouldRecallUsed = True
                    End If
                End If
                If lblnCanCheckRecallCalling Then
                    'Check if there are any user in DE screen
                    If mclsDataHubManager.GetDEScreenStatus(mintProjectID) = False Then
                        lblnShouldRecallUsed = False
                    End If
                End If
            End If
            'If there are any user in the DE screen
            If lblnShouldRecallUsed Then
                'Call the row level changes before preparing for column level changes
                RecallDataChanges(lblnShouldReSort)
                If lblnShouldReSort Then
                    ConductSorting("")
                End If

                'If it's coming from ReEnableDataHub i.e. Load Mapping, then just work on the selected column
                If penmRecallChangesCaller = RecallChangesCaller.ReEnableDataHub Then
                    lobjLoadedDataSource = mstCurrentDataSources.Find(Function(p) p.SourceName = mstrRightClickColName)
                    If lstrEntitiesIDsForDBRecall Is Nothing Then
                        lstrEntitiesIDsForDBRecall = New StringBuilder
                    End If
                    lstActiveDataSources.Add(lobjLoadedDataSource)
                    lstrEntitiesIDsForDBRecall.Append(lobjLoadedDataSource.EntityID)
                    lstrEntitiesIDsForDBRecall.Append(",")

                    If lstrDataEntitiesForDBRecall Is Nothing Then
                        lstrDataEntitiesForDBRecall = New StringBuilder
                    End If
                    lstrDataEntitiesForDBRecall.Append(lobjLoadedDataSource.SourceName)
                    lstrDataEntitiesForDBRecall.Append(",")
                Else
                    'Otherwise, check if the columns in the grid/datatable still exists in the database
                    For Each lobjCurrentDataSources As CurrentDataSources In lstDataEntities
                        lblnCanGetDataFromDB = False
                        If pblnIsFromSnapshot Then
                            If lstSnapshotMissingDataSources IsNot Nothing Then
                                If lstSnapshotMissingDataSources.Count > 0 Then
                                    If lstSnapshotMissingDataSources.Contains(lobjCurrentDataSources.SourceName) Then
                                        lblnDoesColumnExists = False
                                    Else
                                        lblnDoesColumnExists = True
                                    End If
                                End If
                            End If
                        Else
                            If pdtCurrentData.Columns.Contains(lobjCurrentDataSources.SourceName) Then
                                lblnDoesColumnExists = True
                            Else
                                lblnDoesColumnExists = False
                            End If
                        End If

                        'If LastUserID=0 i.e. Column is just added OR if the column was last accessed by current user only then do the following
                        If lobjCurrentDataSources.LastUserID = 0 OrElse lobjCurrentDataSources.LastUserID = CommonCLL.UserID Then
                            'If the column already exists, then simply unhide it
                            If lblnDoesColumnExists Then
                                'Simply Unhide
                                If grdData.Rows.Band.Columns(lobjCurrentDataSources.SourceName).Hidden Then
                                    grdData.Rows.Band.Columns(lobjCurrentDataSources.SourceName).Hidden = False
                                End If
                            Else
                                'Otherwise, check if the column does not exist in the snapshot, then it's data has to be picked from DB
                                lblnCanGetDataFromDB = True
                                If penmRecallChangesCaller = RecallChangesCaller.ColumnList Then
                                    'Add a new column after the last locked column
                                    AddNewColumn(lobjCurrentDataSources, pdtCurrentData, penmRecallChangesCaller)
                                End If
                            End If
                            'If the column was last accessed by someone else then do the following
                        ElseIf lobjCurrentDataSources.LastUserID <> CommonCLL.UserID Then
                            'If it exists already in the grid then simply unhide it
                            If lblnDoesColumnExists Then
                                'Simply Unhide
                                If grdData.Rows.Band.Columns(lobjCurrentDataSources.SourceName).Hidden Then
                                    grdData.Rows.Band.Columns(lobjCurrentDataSources.SourceName).Hidden = False
                                End If
                            Else
                                'Otherwise, check if the column does not exist in the snapshot, then it's data has to be picked from DB
                                lblnCanGetDataFromDB = True
                                'Add a new column and get latest values for it.
                                If penmRecallChangesCaller = RecallChangesCaller.ColumnList Then
                                    AddNewColumn(lobjCurrentDataSources, pdtCurrentData, penmRecallChangesCaller)
                                End If
                            End If
                        End If
                        'If the column has to be picked from DB, then add its name in the list
                        If lblnCanGetDataFromDB Then
                            If lstrEntitiesIDsForDBRecall Is Nothing Then
                                lstrEntitiesIDsForDBRecall = New StringBuilder
                            End If
                            lstActiveDataSources.Add(lobjCurrentDataSources)
                            lstrEntitiesIDsForDBRecall.Append(lobjCurrentDataSources.EntityID)
                            lstrEntitiesIDsForDBRecall.Append(",")

                            If lstrDataEntitiesForDBRecall Is Nothing Then
                                lstrDataEntitiesForDBRecall = New StringBuilder
                            End If
                            lstrDataEntitiesForDBRecall.Append(lobjCurrentDataSources.SourceName)
                            lstrDataEntitiesForDBRecall.Append(",")
                        End If
                    Next
                End If

                'Check if there are any entities for which a DB call is required
                If lstrDataEntitiesForDBRecall IsNot Nothing Then
                    If lstrDataEntitiesForDBRecall.Length > 0 Then
                        lstrEntitiesIDsForDBRecall.Length = lstrEntitiesIDsForDBRecall.Length - 1
                        lstrDataEntitiesForDBRecall.Length = lstrDataEntitiesForDBRecall.Length - 1
                        'If there are, recall the data and update them in the grid
                        GetLockedEntityUpdatedData(lstrEntitiesIDsForDBRecall.ToString, lstrDataEntitiesForDBRecall.ToString, lstActiveDataSources, False, True)
                        If penmRecallChangesCaller = RecallChangesCaller.OnLoad Then
                            ''To set the date column as adjancent to it's parent column in the datatable, when data is fetched from database parent column and associated date column are not adjacent
                            SetGridDataColumnIndex(pdtCurrentData)

                            'Get the index of some static columns in class level variable so that it can be used afterwards
                            GetGridColumnIndex(pdtCurrentData)
                        End If
                    End If
                End If
            End If
            'Get the updated doubt status of the data sources
            If lstrEntitiesIDsForDBRecall IsNot Nothing Then
                GetEntityDoubtStatus(lstrEntitiesIDsForDBRecall.ToString)
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            lstrEntitiesIDsForDBRecall = Nothing
            lstrDataEntitiesForDBRecall = Nothing
            lobjLoadedDataSource = Nothing
            lstActiveDataSources = Nothing
        End Try
    End Sub

    Private Sub AddNewColumn(ByVal lobjCurrentDataSources As CurrentDataSources, ByRef pdtCurrentData As DataTable, ByVal penmRecallChangesCaller As RecallChangesCaller)
        Dim lintNewColumnIndex As Integer
        Dim rootband As UltraGridBand
        Dim lstLockedCurrentDataSources As List(Of CurrentDataSources)
        Dim lintMaxVisibleIndex As Integer
        Try
            If penmRecallChangesCaller = RecallChangesCaller.ColumnList Then
                rootband = grdData.Rows.Band
                lstLockedCurrentDataSources = mstCurrentDataSources.FindAll(Function(p) p.AccessStatus = SourceAccessbility.Locked.ToString)
                If lstLockedCurrentDataSources.Count > 0 Then
                    For Each lobjLockedDataSource As CurrentDataSources In lstLockedCurrentDataSources
                        If lobjLockedDataSource.EntityID = lstLockedCurrentDataSources(0).EntityID Then
                            lintMaxVisibleIndex = rootband.Columns(lobjLockedDataSource.SourceName).Header.VisiblePosition
                            If lobjLockedDataSource.SourceDate.Equals("") = False Then
                                lintMaxVisibleIndex += 1
                            End If
                        Else
                            If rootband.Columns(lobjLockedDataSource.SourceName).Header.VisiblePosition > lintMaxVisibleIndex Then
                                lintMaxVisibleIndex = rootband.Columns(lobjLockedDataSource.SourceName).Header.VisiblePosition
                            End If
                            If lobjLockedDataSource.SourceDate.Equals("") = False Then
                                lintMaxVisibleIndex += 1
                            End If
                        End If
                    Next
                    lintNewColumnIndex = lintMaxVisibleIndex
                    'pdtCurrentData.Columns.Add(lobjCurrentDataSources.SourceName, GetType(String))
                    'pdtCurrentData.Columns(lobjCurrentDataSources.SourceName).SetOrdinal(lintMaxVisibleIndex + 1)
                    'If lobjCurrentDataSources.SourceDate.Equals("") = False Then
                    '    pdtCurrentData.Columns.Add(lobjCurrentDataSources.SourceDate, GetType(String))
                    '    pdtCurrentData.Columns(lobjCurrentDataSources.SourceDate).SetOrdinal(lintMaxVisibleIndex + 2)
                    'End If
                End If
            Else
                lintNewColumnIndex = pdtCurrentData.Columns("Parent").Ordinal
            End If
            'Create the Position column
            If pdtCurrentData.Columns.Contains(lobjCurrentDataSources.SourceName) = False Then
                pdtCurrentData.Columns.Add(lobjCurrentDataSources.SourceName, GetType(String))
                pdtCurrentData.Columns(lobjCurrentDataSources.SourceName).SetOrdinal(lintNewColumnIndex + 1)
            End If

            ''Create the SOF column
            'pdtCurrentData.Columns.Add(mstrSOFColPrefix + lobjCurrentDataSources.SourceName, GetType(Boolean))
            'pdtCurrentData.Columns(mstrSOFColPrefix + lobjCurrentDataSources.SourceName).SetOrdinal(lintNewColumnIndex + 2)

            If lobjCurrentDataSources.SourceDate.Equals("") = False Then
                If pdtCurrentData.Columns.Contains(lobjCurrentDataSources.SourceName) = False Then
                    pdtCurrentData.Columns.Add(lobjCurrentDataSources.SourceDate, GetType(Date))
                    pdtCurrentData.Columns(lobjCurrentDataSources.SourceDate).SetOrdinal(lintNewColumnIndex + 2)
                End If
            End If

            If lobjCurrentDataSources.SourceTypeCode = SourceTypeCode.PBC.ToString Then
                If pdtCurrentData.Columns.Contains(lobjCurrentDataSources.SourceName + mstrFilingDateColSuffix) = False Then
                    pdtCurrentData.Columns.Add(lobjCurrentDataSources.SourceName + mstrSourceColSuffix, GetType(String))
                    pdtCurrentData.Columns.Add(lobjCurrentDataSources.SourceName + mstrFilingDateColSuffix, GetType(String))
                End If
            Else
                If pdtCurrentData.Columns.Contains(lobjCurrentDataSources.SourceName + mstrFilingDateColSuffix) Then
                    pdtCurrentData.Columns.Remove(lobjCurrentDataSources.SourceName + mstrSourceColSuffix)
                    pdtCurrentData.Columns.Remove(lobjCurrentDataSources.SourceName + mstrFilingDateColSuffix)
                End If
            End If
            If lobjCurrentDataSources.SourceTypeCode = SourceTypeCode.RSH.ToString Then
                If pdtCurrentData.Columns.Contains(lobjCurrentDataSources.SourceName + mstrClientSpecificSourceColSuffix) = False Then
                    pdtCurrentData.Columns.Add(lobjCurrentDataSources.SourceName + mstrClientSpecificSourceColSuffix, GetType(String))
                    pdtCurrentData.Columns.Add(lobjCurrentDataSources.SourceName + mstrGenericSourceColSuffix, GetType(String))
                    pdtCurrentData.Columns.Add(lobjCurrentDataSources.SourceName + mstrSourceColSuffix, GetType(String))
                    mstSysColumns.Add(lobjCurrentDataSources.SourceName + mstrGenericSourceColSuffix)
                    mstSysColumns.Add(lobjCurrentDataSources.SourceName + mstrClientSpecificSourceColSuffix)
                End If
            End If

            ''Create the Formula column
            'pdtCurrentData.Columns.Add(lobjCurrentDataSources.SourceName + mstrFormulaColSuffix, GetType(String))
            'pdtCurrentData.Columns(lobjCurrentDataSources.SourceName + mstrFormulaColSuffix).SetOrdinal(lintNewColumnIndex + 4)
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            rootband = Nothing
            lstLockedCurrentDataSources = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' Check if there are any row level changes i.e. Any ADD, CHANGE FUND, DELETE, recall them and make changes in the grid accordingly
    ''' </summary>
    ''' <param name="pblnShouldReSort"></param>
    ''' <remarks></remarks>
    Private Sub RecallDataChanges(ByRef pblnShouldReSort As Boolean)
        Dim lstRecallDataChanges As List(Of RecallData) = Nothing
        Dim lstRecallAddResults As List(Of InvestorFundResults) = Nothing
        Dim lstPreviousProjectRecallData As List(Of PreviousProjectRecallData) = Nothing
        Dim ldtCurrentData As DataTable = grdData.DataSource
        Dim ldrInvestorRow As DataRow = Nothing
        Dim ldrMasterData As DataRow = Nothing
        Dim lblnHasAddReplaceRow As Boolean
        Dim lobjPreviousProjects As PreviousProjects = Nothing
        Dim lintListingID As Integer
        Dim ldrAssociatedData As DataRow = Nothing
        Dim larrDeletingRows() As DataRow = Nothing
        grdData.BeginUpdate()
        grdData.SuspendRowSynchronization()
        Try
            lstRecallDataChanges = New List(Of RecallData)
            lstRecallAddResults = New List(Of InvestorFundResults)
            lstPreviousProjectRecallData = New List(Of PreviousProjectRecallData)
            'Recall the changes from database
            mclsDataHubManager.RecallDataChanges(mintProjectID, lstRecallDataChanges, lstRecallAddResults, lstPreviousProjectRecallData)
            'This table contains the InvestorID, LinkID, FundID and the type of change made
            'ldtRecallDataChanges = ldsResults.Tables(0)
            If lstRecallDataChanges.Count = 0 Then Exit Sub
            'This table contains the data to be added in the grid
            'ldtRecallAddData = ldsResults.Tables(1)
            'Dim lintAddRowCounter As Integer = 0
            lblnHasAddReplaceRow = False
            'Find out the current Max RowNumber so that th next incremental rownumbers can be used for new records
            'To stop the paint event of the grid before the loop so that it's painted only once, after the loop
            'Traverse all the data changes
            For Each lobjRecallData As RecallData In lstRecallDataChanges
                'If it's a DELETE row, then simply remove it
                If lobjRecallData.FlagChangeTypeCode = DataChangeFlagType.DEL.ToString Then
                    'If InvestorID is 0, it means a Fund has been deleted, in that case find that record with the help of Select
                    If lobjRecallData.InvestorID = 0 Then
                        larrDeletingRows = ldtCurrentData.Select("LinkID=" + lobjRecallData.NewLinkID.ToString)
                        If larrDeletingRows IsNot Nothing Then
                            If larrDeletingRows.Length > 0 Then
                                ldrInvestorRow = larrDeletingRows(0)
                            End If
                        End If
                    Else
                        ldrInvestorRow = ldtCurrentData.Rows.Find(New Object() {lobjRecallData.InvestorID, lobjRecallData.NewFundID})
                    End If
                    pblnShouldReSort = False
                    If ldrInvestorRow IsNot Nothing Then
                        ldtCurrentData.Rows.Remove(ldrInvestorRow)
                    End If
                ElseIf lobjRecallData.FlagChangeTypeCode = DataChangeFlagType.RMV.ToString Then
                    ldrInvestorRow = ldtCurrentData.Rows.Find(New Object() {lobjRecallData.InvestorID, lobjRecallData.NewFundID})
                    pblnShouldReSort = False
                    If ldrInvestorRow IsNot Nothing Then
                        ldtCurrentData.Rows.Remove(ldrInvestorRow)
                    End If
                    'Otherwise check if its an ADD row
                ElseIf lobjRecallData.FlagChangeTypeCode = DataChangeFlagType.ADD.ToString Then
                    pblnShouldReSort = True
                    'Otherwise check if it a REPLACE/CHANGE row
                ElseIf lobjRecallData.FlagChangeTypeCode = DataChangeFlagType.RPC.ToString Then
                    pblnShouldReSort = True
                    'Otherwise check if it a Mark Deleted row
                ElseIf lobjRecallData.FlagChangeTypeCode = DataChangeFlagType.MDL.ToString Then
                    pblnShouldReSort = False
                    ldrInvestorRow = ldtCurrentData.Rows.Find(New Object() {lobjRecallData.InvestorID, lobjRecallData.NewFundID})
                    If ldrInvestorRow IsNot Nothing Then
                        MarkEntityDelete(grdData.Rows.GetRowWithListIndex(ldtCurrentData.Rows.IndexOf(ldrInvestorRow)))
                    End If
                    'Otherwise check if any previous project's positions are changed
                ElseIf lobjRecallData.FlagChangeTypeCode = DataChangeFlagType.PPC.ToString Then
                    pblnShouldReSort = True
                End If
                lobjRecallData.IsHandled = True
            Next
            If lstRecallAddResults.Find(Function(p) p.FlagChangeTypeCode = DataChangeFlagType.ADD.ToString OrElse p.FlagChangeTypeCode = DataChangeFlagType.RPC.ToString) IsNot Nothing Then
                SetInvestorFundDetails(lstRecallDataChanges, lstRecallAddResults, False, ldtCurrentData)
                'To set the Flag to go to the database to have fresh DenseRank and FundDenseRank
                mblnAnyChangesInLastProject = True
            End If

            If lstRecallDataChanges.Find(Function(p) p.FlagChangeTypeCode = DataChangeFlagType.PPC.ToString) IsNot Nothing Then
                For Each lobjPPData As PreviousProjectRecallData In lstPreviousProjectRecallData
                    lintListingID = lobjPPData.ListingID
                    lobjPreviousProjects = mstPreviousProjects.Find(Function(p) p.ListingID = lintListingID)
                    ldrInvestorRow = ldtCurrentData.Rows.Find(New Object() {lobjPPData.InvestorID, lobjPPData.NewFundID})
                    If ldrInvestorRow IsNot Nothing Then
                        ldrInvestorRow.Item(lobjPreviousProjects.DeliveryListing) = lobjPPData.Positions
                        SetAssociatedIsSumOfFunds(ldrInvestorRow.Item("InvestorID"), ldrInvestorRow.Item("FundID"), lobjPreviousProjects.DeliveryListing, lobjPPData.IsSumOfFunds)
                        'ldrInvestorRow.Item(mstrSOFColPrefix + lobjPreviousProjects.DeliveryListing) = lobjPPData.IsSumOfFunds
                        SetAssociatedFormula(ldrInvestorRow.Item("InvestorID"), ldrInvestorRow.Item("FundID"), lobjPreviousProjects.DeliveryListing, lobjPPData.Formula)
                        'ldrInvestorRow.Item(lobjPreviousProjects.DeliveryListing + mstrFormulaColSuffix) = lobjPPData.Formula
                    End If
                Next
            End If
            'Update the grid and enable the paint
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            ldrAssociatedData = Nothing
            lstRecallDataChanges = Nothing
            lstRecallAddResults = Nothing
            lstPreviousProjectRecallData = Nothing
            ldtCurrentData = Nothing
            ldrInvestorRow = Nothing
            larrDeletingRows = Nothing
            ldrMasterData = Nothing
            lobjPreviousProjects = Nothing
            grdData.SuspendRowSynchronization()
            grdData.EndUpdate()
            grdData.Update()
        End Try
    End Sub

    Private Sub SetInvestorFundDetails(ByVal lstRecallDataChanges As List(Of RecallData), ByVal lstRecallAddResults As IList(Of InvestorFundResults), ByVal pblnIsFromMaster As Boolean, ByRef ldtCurrentData As DataTable)
        Dim ldrMasterData As DataRow = Nothing
        Dim lobjRecallDataChanges As RecallData
        Dim lintLinkID As Integer
        Dim lintRowNumber As Integer
        'Dim ldrInvestorRow As DataRow = Nothing
        Try
            lintRowNumber = Convert.ToInt32(ldtCurrentData.Compute("max(RowNumber)", String.Empty))
            For Each lobjRecallAddResults As InvestorFundResults In lstRecallAddResults
                If lobjRecallAddResults.FlagChangeTypeCode = DataChangeFlagType.ADD.ToString Then
                    If ldtCurrentData.Rows.Find(New Object() {lobjRecallAddResults.InvestorID, lobjRecallAddResults.FundID}) IsNot Nothing Then
                        Continue For
                    End If
                    ldrMasterData = ldtCurrentData.NewRow
                Else
                    lintLinkID = lobjRecallAddResults.LinkID
                    lobjRecallDataChanges = lstRecallDataChanges.Find(Function(p) p.NewLinkID = lintLinkID)
                    ldrMasterData = ldtCurrentData.Rows.Find(New Object() {lobjRecallDataChanges.OldInvestorID, lobjRecallDataChanges.OldFundID})
                End If

                With lobjRecallAddResults
                    If lobjRecallAddResults.FlagChangeTypeCode = DataChangeFlagType.ADD.ToString Then
                        lintRowNumber += 1
                        If pblnIsFromMaster Then
                            ldrMasterData.Item("UserID") = .UserID
                            ldrMasterData.Item("ProjectID") = .ProjectID
                        Else
                            ldrMasterData.Item("UserID") = CommonCLL.UserID
                            ldrMasterData.Item("ProjectID") = mintProjectID
                        End If
                        ldrMasterData.Item("RowNumber") = lintRowNumber
                        ldrMasterData.Item("IsMasterDB") = .IsMasterDB
                        ldrMasterData.Item("DenseRank") = .DenseRank
                        ldrMasterData.Item("FundDenseRank") = .FundDenseRank
                        ldrMasterData.Item("IsInvestor") = .IsInvestor
                        ldrMasterData.Item("IsManaged") = .IsManaged
                        ldrMasterData.Item("IsCutRow") = .IsCutRow
                    End If

                    ldrMasterData.Item("InvestorID") = .InvestorID
                    ldrMasterData.Item("LinkID") = .LinkID
                    ldrMasterData.Item("FundID") = .FundID
                    ldrMasterData.Item("InvestorName") = .InvestorName
                    ldrMasterData.Item("FundName") = .FundName
                    ldrMasterData.Item("Notes") = .Notes
                    ldrMasterData.Item("Origin") = .Origin
                    ldrMasterData.Item("ID") = .ID
                    ldrMasterData.Item("InvStatusCode") = .InvStatusCode
                    If .FundName.Trim.Equals("") = False Then
                        ldrMasterData.Item("Name") = mstrFundPrefixSpaces + .Name.Trim
                    Else
                        ldrMasterData.Item("Name") = .Name.Trim
                    End If
                    ldrMasterData.Item("MInvestorTypeID") = .MInvestorTypeID
                    ldrMasterData.Item("Head Investor") = .HeadInvestor
                    ldrMasterData.Item("Parent") = .Parent
                    ldrMasterData.Item("Activist") = .Activist
                    ldrMasterData.Item("Type") = .Type
                    ldrMasterData.Item("Style") = .Style
                    ldrMasterData.Item("Turnover") = .Turnover
                    ldrMasterData.Item("City") = .City
                    ldrMasterData.Item("State") = .State
                    ldrMasterData.Item("Country") = .Country
                    ldrMasterData.Item("Region") = .Region
                End With
                If lobjRecallAddResults.FlagChangeTypeCode = DataChangeFlagType.ADD.ToString Then
                    ldtCurrentData.Rows.Add(ldrMasterData)
                End If
            Next
            grdData.Update()
            'grdData.UpdateData()
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            lstRecallAddResults = Nothing
            ldrMasterData = Nothing
        End Try
    End Sub

    Private Sub UpdateInvestorFundDetails(ByVal lstRecallAddResults As IList(Of InvestorFundResults), ByVal pblnIsFromMaster As Boolean, ByVal lintRowNumber As Integer, ByRef ldtCurrentData As DataTable)
        Dim ldrMasterData As DataRow = Nothing
        Try
            For Each lobjRecallAddResults As InvestorFundResults In lstRecallAddResults
                ldrMasterData = ldtCurrentData.NewRow
                lintRowNumber += 1
                With lobjRecallAddResults
                    If pblnIsFromMaster Then
                        ldrMasterData.Item("UserID") = .UserID
                        ldrMasterData.Item("ProjectID") = .ProjectID
                    Else
                        ldrMasterData.Item("UserID") = CommonCLL.UserID
                        ldrMasterData.Item("ProjectID") = mintProjectID
                    End If
                    ldrMasterData.Item("RowNumber") = lintRowNumber
                    ldrMasterData.Item("IsMasterDB") = .IsMasterDB
                    ldrMasterData.Item("RowNumber") = .RowNumber
                    ldrMasterData.Item("DenseRank") = .DenseRank
                    ldrMasterData.Item("FundDenseRank") = .FundDenseRank
                    ldrMasterData.Item("Status") = .Status
                    ldrMasterData.Item("InvestorID") = .InvestorID
                    ldrMasterData.Item("LinkID") = .LinkID
                    ldrMasterData.Item("FundID") = .FundID
                    ldrMasterData.Item("InvestorName") = .InvestorName
                    ldrMasterData.Item("FundName") = .FundName
                    ldrMasterData.Item("IsInvestor") = .IsInvestor
                    ldrMasterData.Item("IsManaged") = .IsManaged
                    ldrMasterData.Item("IsCutRow") = .IsCutRow
                    ldrMasterData.Item("Notes") = .Notes
                    ldrMasterData.Item("Origin") = .Origin
                    ldrMasterData.Item("ID") = .ID
                    ldrMasterData.Item("InvStatusCode") = .InvStatusCode
                    ldrMasterData.Item("Name") = .Name
                    ldrMasterData.Item("MInvestorTypeID") = .MInvestorTypeID
                    ldrMasterData.Item("Head Investor") = .HeadInvestor
                    ldrMasterData.Item("Parent") = .Parent
                    ldrMasterData.Item("Activist") = .Activist
                    ldrMasterData.Item("Type") = .Type
                    ldrMasterData.Item("Style") = .Style
                    ldrMasterData.Item("Turnover") = .Turnover
                    ldrMasterData.Item("City") = .City
                    ldrMasterData.Item("State") = .State
                    ldrMasterData.Item("Country") = .Country
                    ldrMasterData.Item("Region") = .Region
                End With
                ldtCurrentData.Rows.Add(ldrMasterData)
            Next
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            lstRecallAddResults = Nothing
            ldrMasterData = Nothing
        End Try

    End Sub
#End Region

#Region "Custom and Regualar Search And Column Filters"
    ''' <summary>
    ''' To conduct the custom/regular search the grid
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub txtSearch_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtInvestor.KeyDown, txtFund.KeyDown
        'Dim ldsMasterData As DataSet = Nothing
        'Dim ldtMasterData As DataTable = Nothing

        If e.Modifiers = Keys.Control Then
            'On pressing Ctrl+G, If there is a locked column then move the focus on the first row of that locked column, else focus on the name column of the first visible row
            If e.KeyCode = Keys.G Then
                FocusOnFirstLockedCell(False)
            ElseIf e.KeyCode = Keys.M Then
                If menmScreenType = DataHubScreenType.DataEntry Then
                    chkSearchMasterDB.Checked = Not chkSearchMasterDB.Checked
                End If
            End If
        ElseIf e.Modifiers = Keys.None Then
            'Conduct the search on pressing Enter
            If e.KeyCode = Keys.Enter Then
                If bgwSqlWorker.IsBusy = False Then
                    bgwSqlWorker.RunWorkerAsync()
                End If
            End If
        End If
    End Sub

    Private Sub StartSearch()
        Dim lstMasterData As IList(Of InvestorFundResults) = Nothing
        Dim lstMAInvestors As IList(Of MAInvestors) = Nothing
        Dim lstChangeLogData As IList(Of LinkingDetails) = Nothing

        Dim lstrInvSearchSplitText() As String = Nothing
        Dim lstrFundSearchSplitText() As String = Nothing
        Dim lblnIsInvAND As Boolean = False
        Dim lblnIsFundAND As Boolean = False

        Dim lblnShouldReSort As Boolean = False

        Dim lblnIsMandACode As Boolean
        Dim lblnIsChangeLogCode As Boolean
        Dim ldrInvestorRow As DataRow
        Dim lintParentInvestorIndex As Integer

        Dim lstrInvSearchText As String
        Dim lstrFundSearchText As String

        Dim lintHypenIndex As Int16
        Dim lintParentInvestorID As Integer

        Dim ldtCurrentData As DataTable
        If rdbCustomSearch.Checked Then
            CancelOutCutOperation()
        End If
        lblnIsMandACode = False
        lblnIsChangeLogCode = False

        If (Me.IsDisposed) Then Exit Sub

        'If the search text starts with M or A and has integer value at the both sides of a hypen, it means it a M&A search code; Set the IsM&ACode status
        If txtInvestor.Text.Trim.StartsWith("M") OrElse txtInvestor.Text.Trim.StartsWith("A") Then
            lintHypenIndex = txtInvestor.Text.Trim.IndexOf("-")
            If lintHypenIndex <> -1 Then
                If txtInvestor.Text.Length >= lintHypenIndex + 2 Then
                    If Char.IsNumber(txtInvestor.Text.Trim.Substring(lintHypenIndex - 1, 1)) AndAlso Char.IsNumber(txtInvestor.Text.Trim.Substring(lintHypenIndex + 1, 1)) Then
                        lblnIsMandACode = True
                    End If
                End If
            End If
        End If

        'If the search text starts with !, it means its a ChangeLog search; Set the IsChangeLogCode status
        If txtInvestor.Text.Trim.StartsWith("!") Then
            lblnIsChangeLogCode = True
        End If
        If lblnIsMandACode OrElse lblnIsChangeLogCode Then
            If lblnIsMandACode Then
                menmSearchType = SearchTypes.MandA
            Else
                menmSearchType = SearchTypes.ChangeLog
            End If
            If txtFund.InvokeRequired Then
                Me.Invoke(New SetControlValues(AddressOf ChangeControlValues), True)
            End If
            'Me.Invoke(New SetControlValues(AddressOf ChangeControlValues), True)

        ElseIf txtInvestor.Text.Trim.Equals(MessageManager.GetMessage("DEFAULTSEARCHTEXT")) = False AndAlso txtFund.Text.Trim.Equals(MessageManager.GetMessage("DEFAULTSEARCHTEXT")) Then
            'Check if its only an Investor search
            menmSearchType = SearchTypes.OnlyInvestor
        ElseIf (txtInvestor.Text.Trim.Equals(MessageManager.GetMessage("DEFAULTSEARCHTEXT")) OrElse txtInvestor.Text.Trim.Equals("")) AndAlso txtFund.Text.Trim.Equals(MessageManager.GetMessage("DEFAULTSEARCHTEXT")) = False Then
            'Check if its only a Fund search
            menmSearchType = SearchTypes.OnlyFund
        Else
            'Check if its an Investor and Fund search
            menmSearchType = SearchTypes.Both
        End If
        If (Me.IsDisposed) Then Exit Sub

        'Check if its a Custom search
        If rdbCustomSearch.Checked Then
            'Dim lintRowNumber As Integer
            ldtCurrentData = grdData.DataSource
            'Turn off the paint events, so that it does not use the resources un-necessarily
            grdData.BeginUpdate()
            grdData.SuspendRowSynchronization()
            'Change the grid's rows backcolor to normal, if there are any non-project db rows from the previous search
            Me.Invoke(New ChangeColorToNormal(AddressOf ChangeRowColorBackToNormal), ldtCurrentData)

            'Do the row level changes, recall the changes from DB
            Me.Invoke(New RecallDataChange(AddressOf RecallDataChanges), lblnShouldReSort)
            If (Me.IsDisposed) Then Exit Sub


            'Set the Investor search text
            If txtInvestor.Text.Trim.Equals(MessageManager.GetMessage("DEFAULTSEARCHTEXT")) Then
                lstrInvSearchText = ""
            Else
                lstrInvSearchText = txtInvestor.Text.Trim
            End If

            'Set the fund search text
            If txtFund.Text.Trim.Equals(MessageManager.GetMessage("DEFAULTSEARCHTEXT")) Then
                lstrFundSearchText = ""
            Else
                lstrFundSearchText = txtFund.Text.Trim
            End If
            'See if the Master DB records are requested too
            If chkSearchMasterDB.Checked AndAlso (lstrInvSearchText.Equals("") = False OrElse lstrFundSearchText.Equals("") = False) Then
                'Check if it's MandA or ChangeLog search
                If menmSearchType = SearchTypes.MandA OrElse menmSearchType = SearchTypes.ChangeLog Then
                    'If its a MandA search, then get the MandA result set
                    If menmSearchType = SearchTypes.MandA Then
                        mclsDataHubManager.GetMAData(mintProjectID, txtInvestor.Text.Trim, lstMasterData, lstMAInvestors)
                    Else
                        'If its a ChangeLog search, then get the ChangeLog result set
                        mclsDataHubManager.GetChangeLogData(mintProjectID, txtInvestor.Text.Trim, lstMasterData, lstChangeLogData)
                    End If
                    ''Get the searched Master DB records
                    'ldtMasterData = ldsMasterData.Tables(0)
                    ''Get the searched MA Investors
                    'ldtMAInvestors = ldsMasterData.Tables(1)
                Else
                    'Otherwise, check if its a normal custom search
                    'Set the SearchOperaator whether its an AND search or OR search for Investors
                    If lstrInvSearchText.Contains(mstrANDOperator) Then
                        lstrInvSearchSplitText = lstrInvSearchText.Split(mstrANDOperator)
                        lblnIsInvAND = True
                    ElseIf lstrInvSearchText.Contains(mstrOROperator) Then
                        lstrInvSearchSplitText = lstrInvSearchText.Split(mstrOROperator)
                        lblnIsInvAND = False
                    Else
                        lstrInvSearchSplitText = {lstrInvSearchText, ""}
                        lblnIsInvAND = True
                    End If

                    'Set the SearchOperator whether its an AND search or OR search for Funds
                    If lstrFundSearchText.Contains(mstrANDOperator) Then
                        lstrFundSearchSplitText = lstrFundSearchText.Split(mstrANDOperator)
                        lblnIsFundAND = True
                    ElseIf lstrFundSearchText.Contains(mstrOROperator) Then
                        lstrFundSearchSplitText = lstrFundSearchText.Split(mstrOROperator)
                        lblnIsFundAND = False
                    Else
                        lstrFundSearchSplitText = {lstrFundSearchText, ""}
                        lblnIsFundAND = True
                    End If
                    'Get the Master Data from database
                    lstMasterData = mclsDataHubManager.GetMasterData(mintProjectID, lstrInvSearchSplitText(0), lstrInvSearchSplitText(1), rdInvContains.Checked, lblnIsInvAND, lstrFundSearchSplitText(0), lstrFundSearchSplitText(1), rdFundContains.Checked, lblnIsFundAND, menmSearchType)
                End If
                'Get the Master Data from database
                'lstMasterData = mclsDataHubManager.GetMasterData(mintProjectID, lstrInvSearchSplitText(0), lstrInvSearchSplitText(1), rdInvContains.Checked, lblnIsInvAND, lstrFundSearchSplitText(0), lstrFundSearchSplitText(1), rdFundContains.Checked, lblnIsFundAND, menmSearchType)
                If (Me.IsDisposed) Then Exit Sub

                If Not CheckThreadStatus() Then
                    grdData.DataSource = ldtCurrentData
                    Exit Sub
                End If
                If (Me.IsDisposed) Then Exit Sub

                'If there are rows in the Master DB results
                If lstMasterData IsNot Nothing Then
                    If lstMasterData.Count > 0 Then
                        mintLastTranversedInvIndex = -1
                        mblnHasMasterSearchRecords = True
                        'If it's an MandA search, get the parent entity i.e. Merger/Acquirer, so that it can be highlighted
                        If menmSearchType = SearchTypes.MandA Then
                            If lstMAInvestors.Count > 0 Then
                                lintParentInvestorID = lstMAInvestors.Item(0).ParentInvestorID
                            End If
                        Else
                            mblnIsFromMasterSearch = True
                        End If
                        'Add the Master DB rows in the grid's data sources with appropriate RowNumbers
                        'lintRowNumber = Convert.ToInt32(CType(grdData.DataSource, DataTable).Compute("max(RowNumber)", String.Empty))
                        Me.Invoke(New SetInvestorFund(AddressOf SetInvestorFundDetails), Nothing, lstMasterData, True, ldtCurrentData)
                        If lstMasterData.Count > 0 Then
                            lblnShouldReSort = True
                        End If
                        'If it's an MandA search, then find the Parent row and highlight it with a different color
                        If menmSearchType = SearchTypes.MandA Then
                            ldrInvestorRow = CType(grdData.DataSource, DataTable).Rows.Find(New Object() {lintParentInvestorID, 0})
                            lintParentInvestorIndex = CType(grdData.DataSource, DataTable).Rows.IndexOf(ldrInvestorRow)
                            grdData.Rows.GetRowWithListIndex(lintParentInvestorIndex).Appearance.ForeColor = grdData.DisplayLayout.Appearances("MandAParentRow").ForeColor 'MandAParentRow Color.DarkOrange
                        End If
                    End If
                End If
            End If
            If (Me.IsDisposed) Then Exit Sub

            'If there are any Master DB results, then it should be resorted
            If lblnShouldReSort Then
                Me.Invoke(New Sort(AddressOf ConductSorting), String.Empty)
            End If
            'Enable the paint events of the grid
            'grdData.Update()
            grdData.ResumeRowSynchronization()
        End If
        'Now once the Master DB data is added in the grid, conduct the local search on the grid
        'If the search is MandA or ChangeLog, then prepare the CustomAndRegularSearch
        If menmSearchType = SearchTypes.MandA OrElse menmSearchType = SearchTypes.ChangeLog Then
            'PrepareCustomAndRegularSearch(txtInvestor, True, ldtMAInvestors)
        Else
            'Otherwise, If it's a normal search, then prepare the CustomAndRegularSearch
            'PrepareCustomAndRegularSearch(txtInvestor, True, Nothing)
        End If
        mintLastTranversedInvestorID = -1

        If rdbCustomSearch.Checked Then
            grdData.Rows.Band.Columns("InvestorName").Hidden = True
        End If
        'Set the searchresulttype to Custom search
        If menmSearchResultType <> SearchResultType.ColumnFilter Then
            menmSearchResultType = SearchResultType.CustomSearch
        End If
        'Set the search type and radio button accordingly
        Me.Invoke(New AccessControl(AddressOf SetSearchFilterResultText), SearchResultType.CustomSearch)
        'SetSearchFilterResultText(SearchResultType.CustomSearch)
        'Now once the Master DB data is added in the grid, conduct the local search on the grid
        'If the search is MandA or ChangeLog, then prepare the CustomAndRegularSearch
        If menmSearchType = SearchTypes.MandA OrElse menmSearchType = SearchTypes.ChangeLog Then
            Me.Invoke(New PrepareSearch(AddressOf PrepareCustomAndRegularSearch), txtInvestor, True, lstMAInvestors, lstChangeLogData)
        Else
            'Otherwise, If it's a normal search, then prepare the CustomAndRegularSearch
            Me.Invoke(New PrepareSearch(AddressOf PrepareCustomAndRegularSearch), txtInvestor, True, Nothing, Nothing)
        End If
        mblnIsFromMasterSearch = False
        mintLastTranversedInvestorID = -1
        mblnIsFromMasterSearch = False
        grdData.EndUpdate()
        'grdData.UpdateData()

    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function CheckThreadStatus() As Boolean
        If mthdThread IsNot Nothing Then
            If mthdThread.ThreadState = ThreadState.Aborted Then
                Return False
            End If
        End If
        Return True
    End Function

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="lblnValue"></param>
    ''' <remarks></remarks>
    Private Sub ChangeControlValues(ByVal lblnValue As Boolean)
        rdbCustomSearch.Checked = lblnValue
        chkSearchMasterDB.Checked = lblnValue
        txtFund.Clear()
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="lblVisible"></param>
    ''' <remarks></remarks>
    Private Sub ShowLoadingLabel(ByVal lblVisible As Boolean)
        lblDataLoading.Visible = lblVisible
    End Sub

    ''' <summary>
    ''' To change the grid's Master db row's color
    ''' </summary>
    ''' <param name="ldtCurrentData"></param>
    ''' <remarks></remarks>
    Private Sub ChangeRowColorBackToNormal(ByRef ldtCurrentData As DataTable)
        Dim lintRowCounter As Integer
        Dim lugrTraversingRow As UltraGridRow = Nothing
        Try
            If mblnHasMasterSearchRecords Then
                lintRowCounter = ldtCurrentData.Rows.Count - 1
                'Traverse the grid, and change the color back to normal for all Project DB records and delete the Master DB records for the previous search
                While lintRowCounter >= 0
                    If ldtCurrentData.Rows(lintRowCounter).RowState <> DataRowState.Deleted Then
                        If ldtCurrentData.Rows(lintRowCounter).Item("IsMasterDB") Is DBNull.Value Then Continue While
                        If ldtCurrentData.Rows(lintRowCounter).Item("IsMasterDB") = True Then
                            ldtCurrentData.Rows.RemoveAt(lintRowCounter)
                        Else
                            If lintRowCounter >= 0 Then
                                lugrTraversingRow = grdData.Rows.GetRowWithListIndex(lintRowCounter)
                                If lugrTraversingRow IsNot Nothing Then
                                    If lugrTraversingRow.Appearance.ForeColor <> grdData.DisplayLayout.Appearances("GridForeColor").ForeColor Then 'mclrGridForeColor
                                        lugrTraversingRow.Appearance.ForeColor = grdData.DisplayLayout.Appearances("GridForeColor").ForeColor
                                    End If
                                End If
                            End If
                        End If
                    End If
                    lintRowCounter -= 1
                End While
                mblnHasMasterSearchRecords = False
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            lugrTraversingRow = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' To prepare for the Custom and Regular search
    ''' </summary>
    ''' <param name="txtSearch">Search Text</param>
    ''' <param name="pblnIsFromInvestor">Is From Investor</param>
    ''' <param name="lstMAInvestors">MAndA Search Results</param>
    ''' <param name="lstChangeLogData">Change Log Search Results</param>
    ''' <remarks></remarks>
    Private Sub PrepareCustomAndRegularSearch(ByVal txtSearch As TextBox, ByVal pblnIsFromInvestor As Boolean, ByVal lstMAInvestors As IList(Of MAInvestors), ByVal lstChangeLogData As IList(Of LinkingDetails))
        'Take care of Accented characters
        Dim lintSearchRowIndex As Integer
        Dim lstrInvAccentedChar As String = CommonCLL.ReplaceForAccentedChars(txtInvestor.Text.Trim)
        Dim lstrFundAccentedChar As String = CommonCLL.ReplaceForAccentedChars(txtFund.Text.Trim)
        'Prepare the investor search text
        If txtInvestor.Text.Trim.Equals(MessageManager.GetMessage("DEFAULTSEARCHTEXT")) Then
            mstrInvSearchText = ""
        Else
            mstrInvSearchText = lstrInvAccentedChar
        End If

        'Prepare the fund search text
        If txtFund.Text.Trim.Equals(MessageManager.GetMessage("DEFAULTSEARCHTEXT")) Then
            mstrFundSearchText = ""
        Else
            mstrFundSearchText = lstrFundAccentedChar
        End If

        'If the currently selected column's index is greater than Name column, then find the searched text in the next row, otherwise search in the same row
        If grdData.ActiveCell IsNot Nothing Then
            lintSearchRowIndex = grdData.ActiveRow.Index
            If grdData.ActiveCell.Column.Index <= grdData.Rows.Band.Columns("Name").Index Then
                lintSearchRowIndex += 1
            End If
        End If
        'Conduct the custom/regular search
        ConductCustomAndRegularSearch(grdData, lintSearchRowIndex, lstMAInvestors, lstChangeLogData)
    End Sub

    ''' <summary>
    ''' To set the visibility of all rows in the grid
    ''' </summary>
    ''' <param name="pblnIsHide"></param>
    ''' <remarks></remarks>
    Private Sub SetAllRowsVisibility(ByVal pblnIsHide As Boolean)
        For Each lRow As UltraGridRow In grdData.Rows
            lRow.Hidden = pblnIsHide
        Next
    End Sub

    ''' <summary>
    ''' Conduct the Custom and Regular search on grid
    ''' </summary>
    ''' <param name="grdData"></param>
    ''' <param name="lintActiveRowIndex"></param>
    ''' <remarks></remarks>
    Private Sub ConductCustomAndRegularSearch(ByVal grdData As Crystal.CustomControls.CrystalUltraGrid, ByVal lintActiveRowIndex As Integer, ByVal lstMAInvestors As IList(Of MAInvestors), ByVal lstChangeLogData As IList(Of LinkingDetails))
        Dim lblnIsFoundInCurrent = False
        Dim lintCurrentCellIndex As Integer
        Dim lintActiveRowIndexBackup As Integer = lintActiveRowIndex
        Dim lblnAnyMatchFound As Boolean = False
        Dim lenmInvRegularSearchOperator As SearchedTextOperators
        Dim lstrInvSearchText As String
        Dim lenmFundRegularSearchOperator As SearchedTextOperators
        Dim lstrFundSearchText As String
        Dim rootBand As UltraGridBand = grdData.DisplayLayout.Bands(0)
        Dim lblnSuccess As Boolean = False
        Dim lstrInvSearchSplitText() As String = Nothing
        Dim lstrFundSearchSplitText() As String = Nothing
        Dim lstIncludedInvestors As List(Of String) = Nothing
        Dim lstConsiderableInvestors As List(Of String) = Nothing

        Dim lSelectedFilterOperator As FilterLogicalOperator

        Dim lblnIsFirstRow As Boolean = True
        Dim larrIncludedInvestors(0) As String
        Dim larrIncludedFunds(0) As String

        Dim lstrInvCellData As String
        Dim lstrFundCellData As String = ""
        Try
            'grdData.EventManager.SetEnabled(Infragistics.Win.UltraWinGrid.GridEventIds.BeforeRowRegionScroll, False)
            'Set the search text to handle special characters for Regex
            lstrInvSearchText = CommonCLL.ReplaceRegexMetaChars(mstrInvSearchText)
            lstrFundSearchText = CommonCLL.ReplaceRegexMetaChars(mstrFundSearchText)
            'If both i.e. Investor and Fund search text are blank, then Clear all filters and search the radio buttons and SearchType accordinlgy
            If mstrInvSearchText.Equals("") AndAlso mstrFundSearchText.Equals("") Then
                grdData.Rows.Band.ColumnFilters.ClearAllFilters()
                menmSearchResultType = SearchResultType.All
                SetSearchFilterResultText(SearchResultType.All)
                ShowInvestorNameColForColumnFilter()
                Exit Sub
            End If

            'If it's a normal search
            If menmSearchType <> SearchTypes.MandA AndAlso menmSearchType <> SearchTypes.ChangeLog Then
                'Set the SearchOperator whether its an AND search or OR search for Investors
                If lstrInvSearchText.Contains(mstrANDOperator) Then
                    lenmInvRegularSearchOperator = SearchedTextOperators.AND
                ElseIf lstrInvSearchText.Contains(mstrOROperator) Then
                    lenmInvRegularSearchOperator = SearchedTextOperators.OR
                Else
                    lenmInvRegularSearchOperator = SearchedTextOperators.SingleText
                End If

                'Set the SearchOperator whether its an AND search or OR search for Funds
                If lstrFundSearchText.Contains(mstrANDOperator) Then
                    lenmFundRegularSearchOperator = SearchedTextOperators.AND
                ElseIf lstrFundSearchText.Contains(mstrOROperator) Then
                    lenmFundRegularSearchOperator = SearchedTextOperators.OR
                Else
                    lenmFundRegularSearchOperator = SearchedTextOperators.SingleText
                End If

                'Get Investors search texts in array
                If lenmInvRegularSearchOperator = SearchedTextOperators.AND Then
                    lstrInvSearchSplitText = lstrInvSearchText.Split(mstrANDOperator)
                ElseIf lenmInvRegularSearchOperator = SearchedTextOperators.OR Then
                    lstrInvSearchSplitText = lstrInvSearchText.Split(mstrOROperator)
                Else
                    'If does not contain any AND or OR, even then set the values for both operands; the second operand will allow any search
                    If lstrInvSearchText.Equals("") Then
                        lstrInvSearchSplitText = {".{0,1}", ".{0,1}"}
                    Else
                        lstrInvSearchSplitText = {lstrInvSearchText, ".{0,1}"}
                    End If
                End If

                'Get Funds search texts in array
                If lenmFundRegularSearchOperator = SearchedTextOperators.AND Then
                    lstrFundSearchSplitText = lstrFundSearchText.Split(mstrANDOperator)
                ElseIf lenmFundRegularSearchOperator = SearchedTextOperators.OR Then
                    lstrFundSearchSplitText = lstrFundSearchText.Split(mstrOROperator)
                Else
                    'If does not contain any AND or OR, even then set the values for both operands; the second operand will allow any search
                    If lstrFundSearchText.Equals("") Then
                        lstrFundSearchSplitText = {".{0,1}", ".{0,1}"}
                    Else
                        lstrFundSearchSplitText = {lstrFundSearchText, ".{0,1}"}
                    End If
                End If

                'Investors: See if its Begins With, then modify the search accordingly
                If rdInvBeginsWith.Checked AndAlso lstrInvSearchText.Equals("") = False Then
                    lstrInvSearchSplitText(0) = "^" + lstrInvSearchSplitText(0)
                    If lenmInvRegularSearchOperator <> SearchedTextOperators.SingleText Then
                        lstrInvSearchSplitText(1) = "^" + lstrInvSearchSplitText(1)
                    End If
                End If

                'Funds: See if its Begins With, then modify the search accordingly
                If rdFundBeginsWith.Checked AndAlso lstrFundSearchText.Equals("") = False Then
                    lstrFundSearchSplitText(0) = "^" + lstrFundSearchSplitText(0)
                    If lenmFundRegularSearchOperator <> SearchedTextOperators.SingleText Then
                        lstrFundSearchSplitText(1) = "^" + lstrFundSearchSplitText(1)
                    End If
                End If

                'If there is an AND search or a single text search, then consider it as AND search
                If lenmInvRegularSearchOperator = SearchedTextOperators.SingleText OrElse lenmInvRegularSearchOperator = SearchedTextOperators.AND Then
                    lSelectedFilterOperator = FilterLogicalOperator.And
                Else
                    'Otherwise an OR search
                    lSelectedFilterOperator = FilterLogicalOperator.Or
                End If
            End If
            'If it's a Custom Search
            If rdbCustomSearch.Checked Then
                SetAllRowsVisibility(False)
                'First clear all previous filters
                rootBand.ColumnFilters.ClearAllFilters()
                'Check if its a Normal search
                If menmSearchType <> SearchTypes.MandA AndAlso menmSearchType <> SearchTypes.ChangeLog Then
                    'Investor Search: If its only an Investor Search
                    If lstrInvSearchText.Equals("") = False And lstrFundSearchText.Equals("") Then
                        ConductInvestorOnlyCustomSearch(lenmInvRegularSearchOperator, lstrInvSearchSplitText, True)

                        'rootBand.ColumnFilters("InvestorName").FilterConditions.Add(FilterComparisionOperator.Match, lstrInvSearchSplitText(0))
                        ''If its an OR search, then the logical operators between Investor column's itself values should be OR
                        'If lenmInvRegularSearchOperator = SearchedTextOperators.OR Then
                        '    rootBand.ColumnFilters("InvestorName").LogicalOperator = FilterLogicalOperator.Or
                        '    'If its an AND search, then the logical operators between Investor column's itself values should be AND
                        'ElseIf lenmInvRegularSearchOperator = SearchedTextOperators.AND OrElse lenmInvRegularSearchOperator = SearchedTextOperators.SingleText Then
                        '    rootBand.ColumnFilters("InvestorName").LogicalOperator = FilterLogicalOperator.And
                        'End If
                        ''Investor: Add second filter condition, match with the second part of the search text in second condition
                        'rootBand.ColumnFilters("InvestorName").FilterConditions.Add(FilterComparisionOperator.Match, lstrInvSearchSplitText(1))

                        'Then check If its a Fund search
                    ElseIf lstrFundSearchText.Equals("") = False Then
                        ''Investor/Fund Search: Check If it's a Investor/Fund Search, if so, then logic is as following:
                        '1. Find the Matching Investor Name from Investor Search first & Save them in a list
                        '2. Clear the filter and search for the matching funds and all of the Investors
                        '3. Find the Matching Investor Name from Fund Search & Save them in a list
                        '4. Hide the Investor rows if it does not exist it either of the list

                        ''Fund Search: Check If it's a Fund Search, if so, then logic is as following:
                        '1. Search for the matching funds and all of the Investors
                        '2. Find the Matching Investor Name from Fund Search & Save them in a 'Valid Investor' list
                        '3. Hide the Investor rows if it does not exist it the 'Valid Investor' list

                        ConductFundCustomSearch(lstrInvSearchText, lenmInvRegularSearchOperator, lenmFundRegularSearchOperator, lstrInvSearchSplitText, lstrFundSearchSplitText, True)
                        'If lstrInvSearchText.Equals("") = False Then
                        '    rootBand.ColumnFilters("InvestorName").FilterConditions.Add(FilterComparisionOperator.Match, lstrInvSearchSplitText(0))
                        '    'If its an OR search, then the logical operators between Investor column's itself values should be OR
                        '    If lenmInvRegularSearchOperator = SearchedTextOperators.OR Then
                        '        rootBand.ColumnFilters("InvestorName").LogicalOperator = FilterLogicalOperator.Or
                        '        'If its an AND search, then the logical operators between Investor column's itself values should be AND
                        '    ElseIf lenmInvRegularSearchOperator = SearchedTextOperators.AND OrElse lenmInvRegularSearchOperator = SearchedTextOperators.SingleText Then
                        '        rootBand.ColumnFilters("InvestorName").LogicalOperator = FilterLogicalOperator.And
                        '    End If
                        '    'Investor: Add second filter condition, match with the second part of the search text in second condition
                        '    rootBand.ColumnFilters("InvestorName").FilterConditions.Add(FilterComparisionOperator.Match, lstrInvSearchSplitText(1))
                        '    rootBand.ColumnFilters.LogicalOperator = FilterLogicalOperator.And

                        '    rootBand.ColumnFilters("FundName").FilterConditions.Add(FilterComparisionOperator.Equals, FilterCondition.BlankCellValue)
                        '    grdData.DisplayLayout.RefreshFilters()

                        '    lstConsiderableInvestors = New List(Of String)
                        '    If grdData.Rows.GetFilteredInNonGroupByRows.Count > 0 Then
                        '        For Each lRow As UltraGridRow In grdData.Rows.GetFilteredInNonGroupByRows
                        '            lstConsiderableInvestors.Add(lRow.GetCellValue("InvestorName"))
                        '        Next
                        '    End If
                        '    rootBand.ColumnFilters.ClearAllFilters()
                        'End If

                        'rootBand.ColumnFilters("LinkID").FilterConditions.Add(FilterComparisionOperator.Equals, 0)
                        'rootBand.ColumnFilters.LogicalOperator = FilterLogicalOperator.Or
                        ' '''''''''''''''Part 1 Starts: Filter Conditions for including Funds rows only'''''''''''''
                        ''Fund: Add first filter condition, match with the first part of the search text in first condition
                        'rootBand.ColumnFilters("FundName").FilterConditions.Add(FilterComparisionOperator.Match, lstrFundSearchSplitText(0))

                        '' ''If its an OR search, then the logical operators between Investor column's itself values should be OR
                        'If lenmFundRegularSearchOperator = SearchedTextOperators.OR Then
                        '    rootBand.ColumnFilters("FundName").LogicalOperator = FilterLogicalOperator.Or
                        'ElseIf lenmFundRegularSearchOperator = SearchedTextOperators.AND OrElse lenmFundRegularSearchOperator = SearchedTextOperators.SingleText Then
                        '    'If its an AND search, then the logical operators between Investor column's itself values should be AND
                        '    rootBand.ColumnFilters("FundName").LogicalOperator = FilterLogicalOperator.And
                        'End If
                        ''Fund: Add second filter condition, match with the second part of the search text in second condition
                        'rootBand.ColumnFilters("FundName").FilterConditions.Add(FilterComparisionOperator.Match, lstrFundSearchSplitText(1))

                        ''Refresh the filters which will result just to show the funds rows; but we need the associated investor rows too, see the code below for this
                        ''ShowInvestorNameColForColumnFilter()
                        'grdData.DisplayLayout.RefreshFilters()

                        'If grdData.Rows.GetFilteredInNonGroupByRows.Count > 0 Then
                        '    lstIncludedInvestors = New List(Of String)
                        '    For Each lRow As UltraGridRow In grdData.Rows.GetFilteredInNonGroupByRows
                        '        If lstIncludedInvestors.Contains(lRow.GetCellValue("InvestorName")) = False AndAlso lRow.GetCellValue("FundName").Equals("") = False Then
                        '            lstIncludedInvestors.Add(lRow.GetCellValue("InvestorName"))
                        '        End If
                        '    Next
                        'End If
                        'If lstrInvSearchText.Equals("") Then
                        '    For Each lRow As UltraGridRow In grdData.Rows.GetFilteredInNonGroupByRows
                        '        If lstIncludedInvestors.Contains(lRow.GetCellValue("InvestorName")) = False Then
                        '            lRow.Hidden = True
                        '        Else
                        '            lRow.Hidden = False
                        '        End If
                        '    Next
                        'Else
                        '    For Each lRow As UltraGridRow In grdData.Rows.GetFilteredInNonGroupByRows
                        '        If lstIncludedInvestors.Contains(lRow.GetCellValue("InvestorName")) = False OrElse lstConsiderableInvestors.Contains(lRow.GetCellValue("InvestorName")) = False Then
                        '            lRow.Hidden = True
                        '        Else
                        '            lRow.Hidden = False
                        '        End If
                        '    Next
                        'End If
                    End If
                Else
                    'If it's an MandA OR ChangeLog search
                    rootBand.ColumnFilters.LogicalOperator = FilterLogicalOperator.And
                    'Just filter in the Investors found in MAInvestor result set
                    If menmSearchType = SearchTypes.MandA Then
                        If lstMAInvestors.Count = 0 Then
                            rootBand.ColumnFilters("InvestorName").FilterConditions.Add(FilterComparisionOperator.Equals, "")
                        Else
                            For Each lobjMAInvestor As MAInvestors In lstMAInvestors
                                rootBand.ColumnFilters("InvestorName").FilterConditions.Add(FilterComparisionOperator.Equals, lobjMAInvestor.InvestorName)
                                rootBand.ColumnFilters("InvestorName").LogicalOperator = FilterLogicalOperator.Or
                            Next
                        End If
                    ElseIf menmSearchType = SearchTypes.ChangeLog Then
                        If lstChangeLogData IsNot Nothing Then
                            For Each lobjChangeLogData As LinkingDetails In lstChangeLogData
                                rootBand.ColumnFilters("InvestorName").FilterConditions.Add(FilterComparisionOperator.Equals, lobjChangeLogData.InvestorName)
                                rootBand.ColumnFilters("InvestorName").LogicalOperator = FilterLogicalOperator.Or

                                rootBand.ColumnFilters("FundName").FilterConditions.Add(FilterComparisionOperator.Equals, lobjChangeLogData.FundName)
                                rootBand.ColumnFilters("FundName").LogicalOperator = FilterLogicalOperator.Or
                            Next
                            If lstChangeLogData.Count = 0 Then
                                rootBand.ColumnFilters("InvestorName").FilterConditions.Add(FilterComparisionOperator.Equals, FilterCondition.BlankCellValue)
                            Else
                                rootBand.ColumnFilters("FundName").FilterConditions.Add(FilterComparisionOperator.Equals, FilterCondition.BlankCellValue)
                            End If
                        End If
                    End If
                    'Refresh the search filter results
                    grdData.DisplayLayout.RefreshFilters()
                End If
            Else
                'Otherwise, if it a Regular search
                'If there is no filtered in row then exit
                If grdData.ActiveRow Is Nothing OrElse grdData.Rows.FilteredInRowCount = 0 Then Exit Sub
                If grdData.ActiveCell Is Nothing Then
                    grdData.ActiveRow.Cells(0).Activated = True
                Else
                    lintCurrentCellIndex = grdData.ActiveCell.Column.Index + 1
                End If
                'Traverse starting from the current row to end unless it finds a match
                While lintActiveRowIndex < grdData.Rows.Count
                    'Ignore if the row is filtered out
                    If grdData.Rows(lintActiveRowIndex).IsFilteredOut = False Then
                        lstrFundCellData = ""
                        'Get the InvestorName
                        lstrInvCellData = grdData.Rows(lintActiveRowIndex).GetCellValue("InvestorName").ToString
                        If grdData.Rows(lintActiveRowIndex).GetCellValue("LinkID") <> 0 Then
                            'Get the FundName, if its an Fund row
                            lstrFundCellData = grdData.Rows(lintActiveRowIndex).GetCellValue("FundName").ToString.Trim
                        End If
                        'Set the search text in array
                        If lenmFundRegularSearchOperator = SearchedTextOperators.SingleText Then
                            If lstrFundSearchText.Equals("") Then
                                If lstrInvSearchText.Equals("") Then
                                    lstrFundSearchSplitText = {".{0,1}", ".{0,1}"}
                                Else
                                    If lstrFundCellData.Equals("") Then
                                        lstrFundSearchSplitText = {"", ""}
                                    Else
                                        lstrFundSearchSplitText = {".{0,-1}", ".{0,-1}"}
                                    End If
                                End If
                            End If
                        End If

                        'Condition 1 Includes: 1. Only the Investor is searched 2. Only the Fund is searched 3. Investor has AND operator and Fund has single text
                        '4. Investor has single text and Fund has AND operator 5. Investor & Fund both have AND operator
                        If (lenmInvRegularSearchOperator = SearchedTextOperators.SingleText AndAlso lenmFundRegularSearchOperator = SearchedTextOperators.SingleText) _
                            OrElse (lenmInvRegularSearchOperator = SearchedTextOperators.AND AndAlso lenmFundRegularSearchOperator = SearchedTextOperators.SingleText) _
                            OrElse (lenmInvRegularSearchOperator = SearchedTextOperators.SingleText AndAlso lenmFundRegularSearchOperator = SearchedTextOperators.AND) _
                            OrElse (lenmInvRegularSearchOperator = SearchedTextOperators.AND AndAlso lenmFundRegularSearchOperator = SearchedTextOperators.AND) _
                            Then
                            If (Regex.Match(lstrInvCellData, lstrInvSearchSplitText(0), RegexOptions.IgnoreCase).Success AndAlso _
                            Regex.Match(lstrInvCellData, lstrInvSearchSplitText(1), RegexOptions.IgnoreCase).Success) AndAlso _
                            (Regex.Match(lstrFundCellData, lstrFundSearchSplitText(0), RegexOptions.IgnoreCase).Success AndAlso _
                            Regex.Match(lstrFundCellData, lstrFundSearchSplitText(1), RegexOptions.IgnoreCase).Success) _
                            Then
                                lblnSuccess = True
                            Else
                                lblnSuccess = False
                            End If
                            'Condition 2 Includes: The Investor has OR operator and Fund has single text
                        ElseIf (lenmInvRegularSearchOperator = SearchedTextOperators.OR AndAlso lenmFundRegularSearchOperator = SearchedTextOperators.SingleText) _
                            Then
                            If (Regex.Match(lstrInvCellData, lstrInvSearchSplitText(0), RegexOptions.IgnoreCase).Success OrElse _
                            Regex.Match(lstrInvCellData, lstrInvSearchSplitText(1), RegexOptions.IgnoreCase).Success) AndAlso _
                            (Regex.Match(lstrFundCellData, lstrFundSearchSplitText(0), RegexOptions.IgnoreCase).Success AndAlso _
                            Regex.Match(lstrFundCellData, lstrFundSearchSplitText(1), RegexOptions.IgnoreCase).Success) _
                            Then
                                lblnSuccess = True
                            Else
                                lblnSuccess = False
                            End If
                            'Condition 3 Includes: The Investor has single text and Fund has OR operator
                        ElseIf (lenmInvRegularSearchOperator = SearchedTextOperators.SingleText AndAlso lenmFundRegularSearchOperator = SearchedTextOperators.OR) _
                            Then
                            If (Regex.Match(lstrInvCellData, lstrInvSearchSplitText(0), RegexOptions.IgnoreCase).Success AndAlso _
                            Regex.Match(lstrInvCellData, lstrInvSearchSplitText(1), RegexOptions.IgnoreCase).Success) AndAlso _
                            (Regex.Match(lstrFundCellData, lstrFundSearchSplitText(0), RegexOptions.IgnoreCase).Success OrElse _
                            Regex.Match(lstrFundCellData, lstrFundSearchSplitText(1), RegexOptions.IgnoreCase).Success) _
                            Then
                                lblnSuccess = True
                            Else
                                lblnSuccess = False
                            End If
                            'Condition 4 Includes: The Investor has AND operator and Fund has OR operator
                        ElseIf lenmInvRegularSearchOperator = SearchedTextOperators.AND AndAlso lenmFundRegularSearchOperator = SearchedTextOperators.OR Then
                            If (Regex.Match(lstrInvCellData, lstrInvSearchSplitText(0), RegexOptions.IgnoreCase).Success AndAlso _
                            Regex.Match(lstrInvCellData, lstrInvSearchSplitText(1), RegexOptions.IgnoreCase).Success) AndAlso _
                            (Regex.Match(lstrFundCellData, lstrFundSearchSplitText(0), RegexOptions.IgnoreCase).Success OrElse _
                            Regex.Match(lstrFundCellData, lstrFundSearchSplitText(1), RegexOptions.IgnoreCase).Success) _
                            Then
                                lblnSuccess = True
                            Else
                                lblnSuccess = False
                            End If
                            'Condition 5 Includes: The Investor has OR operator and Fund has AND operator
                        ElseIf lenmInvRegularSearchOperator = SearchedTextOperators.OR AndAlso lenmFundRegularSearchOperator = SearchedTextOperators.AND Then
                            If (Regex.Match(lstrInvCellData, lstrInvSearchSplitText(0), RegexOptions.IgnoreCase).Success OrElse _
                            Regex.Match(lstrInvCellData, lstrInvSearchSplitText(1), RegexOptions.IgnoreCase).Success) AndAlso _
                            (Regex.Match(lstrFundCellData, lstrFundSearchSplitText(0), RegexOptions.IgnoreCase).Success AndAlso _
                            Regex.Match(lstrFundCellData, lstrFundSearchSplitText(1), RegexOptions.IgnoreCase).Success) _
                            Then
                                lblnSuccess = True
                            Else
                                lblnSuccess = False
                            End If
                            'Condition 6 Includes: The Investor and Fund both has OR operator
                        ElseIf (lenmInvRegularSearchOperator = SearchedTextOperators.OR AndAlso lenmFundRegularSearchOperator = SearchedTextOperators.OR) _
                            Then
                            If (Regex.Match(lstrInvCellData, lstrInvSearchSplitText(0), RegexOptions.IgnoreCase).Success OrElse _
                            Regex.Match(lstrInvCellData, lstrInvSearchSplitText(1), RegexOptions.IgnoreCase).Success) AndAlso _
                            (Regex.Match(lstrFundCellData, lstrFundSearchSplitText(0), RegexOptions.IgnoreCase).Success OrElse _
                            Regex.Match(lstrFundCellData, lstrFundSearchSplitText(1), RegexOptions.IgnoreCase).Success) _
                            Then
                                lblnSuccess = True
                            Else
                                lblnSuccess = False
                            End If
                        End If
                        'If found, unselect the currently selected cell and select the found cell
                        If lblnSuccess Then
                            lblnAnyMatchFound = True
                            If grdData.Selected.Cells.Count > 0 Then
                                grdData.Selected.Cells(0).Selected = False
                            End If
                            grdData.ActiveCell.Activated = False
                            'Make the found cell as active, Make the row visible and scroll it to the middle
                            If CommonCLL.IsRowVisible(grdData, grdData.Rows(lintActiveRowIndex)) = False Then
                                CommonCLL.ScrollRowToMiddle(grdData.Rows(lintActiveRowIndex))
                            End If
                            grdData.Rows(lintActiveRowIndex).Cells("Name").Activated = True
                            grdData.Rows(lintActiveRowIndex).Cells("Name").Selected = True
                            grdData.DisplayLayout.ColScrollRegions(0).ScrollColIntoView(grdData.ActiveCell.Column)
                            'Set the boolean variable that it's found in the currently active row
                            lblnIsFoundInCurrent = True
                            Exit While
                        End If
                    End If
                    lintCurrentCellIndex = 0
                    lintActiveRowIndex += 1
                End While
                'Recall the procedure with the next row, if the pharse not found in the currently active row and also if grid has not reached to its end
                If lblnIsFoundInCurrent = False AndAlso lintActiveRowIndex <> grdData.Rows.Count Then
                    ConductCustomAndRegularSearch(grdData, grdData.ActiveRow.Index + 1, lstMAInvestors, lstChangeLogData)
                End If
                'If reached the last row, then restart from the first
                If lintActiveRowIndexBackup = 0 AndAlso lblnAnyMatchFound = False Then
                Else
                    If lintActiveRowIndex = grdData.Rows.Count Then
                        ConductCustomAndRegularSearch(grdData, 0, lstMAInvestors, lstChangeLogData)
                    End If
                End If
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            'grdData.EventManager.SetEnabled(Infragistics.Win.UltraWinGrid.GridEventIds.BeforeRowRegionScroll, True)
            lenmInvRegularSearchOperator = Nothing
            lSelectedFilterOperator = Nothing
            lenmFundRegularSearchOperator = Nothing
        End Try
    End Sub

    Private Sub ConductInvestorOnlyCustomSearch(ByVal lenmInvRegularSearchOperator As SearchedTextOperators, ByVal lstrInvSearchSplitText() As String, _
                                                ByVal pblnIsFromSearch As Boolean)
        Dim rootBand As UltraGridBand = grdData.DisplayLayout.Bands(0)
        If pblnIsFromSearch Then
            rootBand.ColumnFilters("InvestorName").FilterConditions.Add(FilterComparisionOperator.Match, lstrInvSearchSplitText(0))
            'If its an OR search, then the logical operators between Investor column's itself values should be OR
            If lenmInvRegularSearchOperator = SearchedTextOperators.OR Then
                rootBand.ColumnFilters("InvestorName").LogicalOperator = FilterLogicalOperator.Or
                'If its an AND search, then the logical operators between Investor column's itself values should be AND
            ElseIf lenmInvRegularSearchOperator = SearchedTextOperators.AND OrElse lenmInvRegularSearchOperator = SearchedTextOperators.SingleText Then
                rootBand.ColumnFilters("InvestorName").LogicalOperator = FilterLogicalOperator.And
            End If
            'Investor: Add second filter condition, match with the second part of the search text in second condition
            rootBand.ColumnFilters("InvestorName").FilterConditions.Add(FilterComparisionOperator.Match, lstrInvSearchSplitText(1))
        Else
            rootBand.ColumnFilters("InvestorName").FilterConditions.Add(FilterComparisionOperator.Equals, lstrInvSearchSplitText(0))
        End If
    End Sub

    ''' <summary>
    ''' To conduct the Investor/Fund OR Fund search
    ''' </summary>
    ''' <param name="lstrInvSearchText"></param>
    ''' <param name="lenmInvRegularSearchOperator"></param>
    ''' <param name="lenmFundRegularSearchOperator"></param>
    ''' <param name="lstrInvSearchSplitText"></param>
    ''' <param name="lstrFundSearchSplitText"></param>
    ''' <remarks></remarks>
    Private Sub ConductFundCustomSearch(ByVal lstrInvSearchText As String, ByVal lenmInvRegularSearchOperator As SearchedTextOperators, _
                                        ByVal lenmFundRegularSearchOperator As SearchedTextOperators, _
                                        ByVal lstrInvSearchSplitText() As String, ByVal lstrFundSearchSplitText() As String, ByVal pblnIsFromSearch As Boolean)
        ''Investor/Fund Search: Check If it's a Investor/Fund Search, if so, then logic is as following:
        '1. Find the Matching Investor Name from Investor Search first & Save them in a list
        '2. Clear the filter and search for the matching funds and all of the Investors
        '3. Find the Matching Investor Name from Fund Search & Save them in a list
        '4. Hide the Investor rows if it does not exist it either of the list

        ''Fund Search: Check If it's a Fund Search, if so, then logic is as following:
        '1. Search for the matching funds and all of the Investors
        '2. Find the Matching Investor Name from Fund Search & Save them in a 'Valid Investor' list
        '3. Hide the Investor rows if it does not exist it the 'Valid Investor' list

        Dim rootBand As UltraGridBand = grdData.DisplayLayout.Bands(0)
        Dim lstConsiderableInvestors As List(Of String) = Nothing
        Dim lstIncludedInvestors As List(Of String) = Nothing
        If lstrInvSearchText.Equals("") = False Then
            lstConsiderableInvestors = New List(Of String)
            If pblnIsFromSearch Then
                rootBand.ColumnFilters("InvestorName").FilterConditions.Add(FilterComparisionOperator.Match, lstrInvSearchSplitText(0))
                'If its an OR search, then the logical operators between Investor column's itself values should be OR
                If lenmInvRegularSearchOperator = SearchedTextOperators.OR Then
                    rootBand.ColumnFilters("InvestorName").LogicalOperator = FilterLogicalOperator.Or
                    'If its an AND search, then the logical operators between Investor column's itself values should be AND
                ElseIf lenmInvRegularSearchOperator = SearchedTextOperators.AND OrElse lenmInvRegularSearchOperator = SearchedTextOperators.SingleText Then
                    rootBand.ColumnFilters("InvestorName").LogicalOperator = FilterLogicalOperator.And
                End If
                'Investor: Add second filter condition, match with the second part of the search text in second condition
                rootBand.ColumnFilters("InvestorName").FilterConditions.Add(FilterComparisionOperator.Match, lstrInvSearchSplitText(1))

                rootBand.ColumnFilters.LogicalOperator = FilterLogicalOperator.And
                rootBand.ColumnFilters("FundName").FilterConditions.Add(FilterComparisionOperator.Equals, FilterCondition.BlankCellValue)
                grdData.DisplayLayout.RefreshFilters()

                If grdData.Rows.GetFilteredInNonGroupByRows.Count > 0 Then
                    For Each lRow As UltraGridRow In grdData.Rows.GetFilteredInNonGroupByRows
                        lstConsiderableInvestors.Add(lRow.GetCellValue("InvestorName"))
                    Next
                End If
            Else
                For Each lstrLinkedInvestor As String In lstrInvSearchSplitText
                    lstConsiderableInvestors.Add(lstrLinkedInvestor)
                Next
            End If
            rootBand.ColumnFilters.ClearAllFilters()
        End If
        rootBand.ColumnFilters("LinkID").FilterConditions.Add(FilterComparisionOperator.Equals, 0)
        rootBand.ColumnFilters.LogicalOperator = FilterLogicalOperator.Or
        '''''''''''''''Part 1 Starts: Filter Conditions for including Funds rows only'''''''''''''
        If pblnIsFromSearch Then
            'Fund: Add first filter condition, match with the first part of the search text in first condition
            rootBand.ColumnFilters("FundName").FilterConditions.Add(FilterComparisionOperator.Match, lstrFundSearchSplitText(0))

            ' ''If its an OR search, then the logical operators between Investor column's itself values should be OR
            If lenmFundRegularSearchOperator = SearchedTextOperators.OR Then
                rootBand.ColumnFilters("FundName").LogicalOperator = FilterLogicalOperator.Or
            ElseIf lenmFundRegularSearchOperator = SearchedTextOperators.AND OrElse lenmFundRegularSearchOperator = SearchedTextOperators.SingleText Then
                'If its an AND search, then the logical operators between Investor column's itself values should be AND
                rootBand.ColumnFilters("FundName").LogicalOperator = FilterLogicalOperator.And
            End If
            'Fund: Add second filter condition, match with the second part of the search text in second condition
            rootBand.ColumnFilters("FundName").FilterConditions.Add(FilterComparisionOperator.Match, lstrFundSearchSplitText(1))
        Else
            'Fund: Add first filter condition, match with the first part of the search text in first condition
            rootBand.ColumnFilters("FundName").FilterConditions.Add(FilterComparisionOperator.Equals, lstrFundSearchSplitText(0))
        End If

        'Refresh the filters which will result just to show the funds rows; but we need the associated investor rows too, see the code below for this
        'ShowInvestorNameColForColumnFilter()
        grdData.DisplayLayout.RefreshFilters()

        If grdData.Rows.GetFilteredInNonGroupByRows.Count > 0 Then
            lstIncludedInvestors = New List(Of String)
            For Each lRow As UltraGridRow In grdData.Rows.GetFilteredInNonGroupByRows
                If lstIncludedInvestors.Contains(lRow.GetCellValue("InvestorName")) = False AndAlso lRow.GetCellValue("FundName").Equals("") = False Then
                    lstIncludedInvestors.Add(lRow.GetCellValue("InvestorName"))
                End If
            Next
        End If
        If lstrInvSearchText.Equals("") Then
            For Each lRow As UltraGridRow In grdData.Rows.GetFilteredInNonGroupByRows
                If lstIncludedInvestors.Contains(lRow.GetCellValue("InvestorName")) = False Then
                    lRow.Hidden = True
                Else
                    lRow.Hidden = False
                End If
            Next
        Else
            For Each lRow As UltraGridRow In grdData.Rows.GetFilteredInNonGroupByRows
                If lstIncludedInvestors.Contains(lRow.GetCellValue("InvestorName")) = False OrElse lstConsiderableInvestors.Contains(lRow.GetCellValue("InvestorName")) = False Then
                    lRow.Hidden = True
                Else
                    lRow.Hidden = False
                End If
            Next
        End If
    End Sub

    ''' <summary>
    ''' To toggle the InvestorName if column filter is selected.
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ShowInvestorNameColForColumnFilter()
        'If column filter is selected, which may result showing only the funds row, hence the accompanying Investor Name is required too. Hide it otherwise.
        If grdData.Rows.GetFilteredOutNonGroupByRows.Count > 0 Then
            grdData.Rows.Band.Columns("InvestorName").Hidden = False
            grdData.Rows.Band.Columns("InvestorName").PerformAutoResize(PerformAutoSizeType.VisibleRows)
        Else
            grdData.Rows.Band.Columns("InvestorName").Hidden = True
        End If
    End Sub

    ''' <summary>
    ''' To set the Search Result type at class level that would be used at various places
    ''' </summary>
    ''' <param name="penmSearchResultType"></param>
    ''' <remarks></remarks>
    Private Sub SetSearchFilterResultText(ByVal penmSearchResultType As SearchResultType)
        If penmSearchResultType = SearchResultType.All Then
            rdbResults.Text = "Search/Filter Results"
            rdAll.Checked = True
            SetAllRowsVisibility(False)
        ElseIf penmSearchResultType = SearchResultType.CustomSearch Then
            rdbResults.Text = "Custom Search Results"
            rdbResults.Checked = True
        ElseIf penmSearchResultType = SearchResultType.ColumnFilter Then
            rdbResults.Text = "Column Filter Results"
            rdbResults.Checked = True
        End If
    End Sub

    ''' <summary>
    ''' Conduct the sorting
    ''' </summary>
    ''' <param name="pstrDeliveryListing"></param>
    ''' <remarks></remarks>
    Private Sub ConductSorting(ByVal pstrDeliveryListing As String)
        Dim sqlBulkCopy As System.Data.SqlClient.SqlBulkCopy = Nothing
        'Dim lstUpdatedSortData As IList(Of UpdatedSortData) = Nothing
        Dim ldtUpdatedSortData As DataTable = Nothing
        Dim ldtCurrentData As DataTable = Nothing
        Dim lintRowCounter As Integer = 0
        Try
            'If the selected sort order is Ascending
            If menmSortingOn = SortingOn.Ascending Then
                'Remove the previous sorting columns
                grdData.Rows.Band.Columns("DenseRank").SortIndicator = SortIndicator.None
                grdData.Rows.Band.Columns("FundDenseRank").SortIndicator = SortIndicator.None

                'grdData.Rows.Band.Columns(mstrDeliveryListingToSort).SortComparer = Nothing
                'grdData.Rows.Band.Columns(mstrDeliveryListingToSort).SortIndicator = SortIndicator.None

                'Give the new Sorting columns for Ascending order
                grdData.Rows.Band.Columns("InvestorName").SortIndicator = SortIndicator.Ascending
                grdData.Rows.Band.Columns("IsInvestor").SortIndicator = SortIndicator.Descending
                grdData.Rows.Band.Columns("IsManaged").SortIndicator = SortIndicator.Descending
                grdData.Rows.Band.Columns("FundName").SortIndicator = SortIndicator.Ascending
                'grdData.Rows.Band.ResetSortedColumns()
            Else
                'If mstrDeliveryListingToSort <> pstrDeliveryListing Then
                '    grdData.Rows.Band.Columns(mstrDeliveryListingToSort).SortComparer = Nothing
                'End If
                'If grdData.Rows.Band.Columns(pstrDeliveryListing).SortComparer Is Nothing Then
                '    grdData.Rows.Band.Columns(pstrDeliveryListing).SortComparer = New NumericComparer
                'End If

                'If the sort order is [Decending Positions] then check if there are any changes in the positions of that previous project; if there are any changes 
                'then send the data to the database for quick sorting and then makes changes at the front end accordingly
                If mblnAnyChangesInLastProject OrElse mstrDeliveryListingToSort <> pstrDeliveryListing Then
                    ''Clear the Staging Sort table for the current UserID and ProjectID
                    CommonManager.ClearDHSortBulkStagingTable("STG_SortDHData", CommonCLL.UserID, mintProjectID)
                    sqlBulkCopy = New System.Data.SqlClient.SqlBulkCopy(mstrConnectionstring)
                    'Define column mappings to specify the columnn/data to be saved in staging table
                    sqlBulkCopy.DestinationTableName = "STG_SortDHData"
                    sqlBulkCopy.ColumnMappings.Add("RowNumber", "RowNumber")
                    sqlBulkCopy.ColumnMappings.Add("InvestorID", "InvestorID")
                    sqlBulkCopy.ColumnMappings.Add("LinkID", "LinkID")
                    sqlBulkCopy.ColumnMappings.Add("Name", "Name")
                    If pstrDeliveryListing.Equals("") = False Then
                        sqlBulkCopy.ColumnMappings.Add("[" + pstrDeliveryListing + "]", "Position")
                    End If
                    sqlBulkCopy.ColumnMappings.Add("IsManaged", "IsManaged")
                    sqlBulkCopy.ColumnMappings.Add("ProjectID", "ProjectID")
                    sqlBulkCopy.ColumnMappings.Add("UserID", "UserID")

                    ldtCurrentData = grdData.DataSource
                    sqlBulkCopy.WriteToServer(ldtCurrentData)
                    sqlBulkCopy.Close()
                    sqlBulkCopy = Nothing

                    'Get the sorted Position data from the database

                    ldtUpdatedSortData = mclsDataHubManager.GetSortedData(mintProjectID, menmSortingOn)
                    SetPrimaryKey(ldtUpdatedSortData)
                    ldtCurrentData.AcceptChanges()
                    ldtCurrentData.Merge(ldtUpdatedSortData, False, MissingSchemaAction.Ignore)

                    'lstUpdatedSortData = mclsDataHubManager.GetSortedData(mintProjectID, menmSortingOn)
                    ''Update the DenseRank and FundDenseRank, which will be used for Position wise sorting
                    'While lintRowCounter < lstUpdatedSortData.Count
                    '    ldtCurrentData.Rows(lintRowCounter).Item("DenseRank") = lstUpdatedSortData.Item(lintRowCounter).DenseRank
                    '    ldtCurrentData.Rows(lintRowCounter).Item("FundDenseRank") = lstUpdatedSortData.Item(lintRowCounter).FundDenseRank
                    '    lintRowCounter += 1
                    'End While
                    'Update the grid
                    grdData.UpdateData()
                End If

                'Change the sort indicator to Position sorting
                grdData.Rows.Band.Columns("InvestorName").SortIndicator = SortIndicator.None
                grdData.Rows.Band.Columns("IsInvestor").SortIndicator = SortIndicator.None
                grdData.Rows.Band.Columns("IsManaged").SortIndicator = SortIndicator.None
                grdData.Rows.Band.Columns("FundName").SortIndicator = SortIndicator.None

                'grdData.Rows.Band.Columns(pstrDeliveryListing).SortIndicator = SortIndicator.Descending

                grdData.Rows.Band.Columns("DenseRank").SortIndicator = SortIndicator.Ascending
                grdData.Rows.Band.Columns("FundDenseRank").SortIndicator = SortIndicator.Ascending
                mblnAnyChangesInLastProject = False
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            sqlBulkCopy = Nothing
            ldtUpdatedSortData = Nothing
            ldtCurrentData = Nothing
        End Try
    End Sub

#End Region

#Region "Add New Investor and Funds"

    ''' <summary>
    ''' Add the Funds of newly added investor.
    ''' </summary>
    ''' <param name="intInvestorID"></param>
    ''' <remarks></remarks>
    Private Sub AddNewLinkedFunds(ByVal intInvestorID As Integer)
        Dim ldtGridData As DataTable
        Dim ldRowGrid As DataRow
        Dim FilterQuery As String
        Dim Excel() As DataRow
        Dim llstLinkedFunds As List(Of AddNewInvestor)
        Dim lintEntityId As Integer
        Try
            ldtGridData = New DataTable
            grdData.BeginUpdate()
            grdData.SuspendRowSynchronization()
            'Retrive the funds of the investor.
            llstLinkedFunds = mclsDataHubManager.GetLinkedFunds(intInvestorID, mintProjectID, CommonCLL.UserID)
            lintEntityId = GetEntityID()
            ldtGridData = CType(grdData.DataSource, DataTable)
            FilterQuery = "InvestorID ='" + intInvestorID.ToString + "'"
            Excel = ldtGridData.Select(FilterQuery)
            If Excel.Length = 0 Then
                ldRowGrid = ldtGridData.NewRow()
                MakeNewFundRow(mlstFundInvestor(0), ldRowGrid)
                ldtGridData.Rows.Add(ldRowGrid)
                ldtGridData.AcceptChanges()
                AddDataInSourceTracking(lintEntityId, ldRowGrid("InvestorID"), ldRowGrid("LinkID"))
            End If

            'Add the newly linked investor to grid.
            For Each llstLinkedFund As AddNewInvestor In llstLinkedFunds
                ldRowGrid = ldtGridData.NewRow()
                If llstLinkedFund.IsInvestor Then
                    FilterQuery = "InvestorID ='" + llstLinkedFund.InvestorID.ToString + "'"
                    Excel = ldtGridData.Select(FilterQuery)
                    'Else import row.
                    If Excel.Length = 0 Then
                        MakeNewFundRow(llstLinkedFund, ldRowGrid)
                        ldtGridData.Rows.Add(ldRowGrid)
                        AddDataInSourceTracking(lintEntityId, ldRowGrid("InvestorID"), ldRowGrid("LinkID"))
                    End If
                Else
                    ''If it is Fund row, and already exist in grid. Skip Import Row.
                    FilterQuery = "InvestorID ='" + llstLinkedFund.InvestorID.ToString + "' And FundID ='" + llstLinkedFund.FundID.ToString + "'"
                    Excel = ldtGridData.Select(FilterQuery)
                    'Else import row.
                    If Excel.Length = 0 Then
                        MakeNewFundRow(llstLinkedFund, ldRowGrid)
                        ldtGridData.Rows.Add(ldRowGrid)
                        AddDataInSourceTracking(lintEntityId, ldRowGrid("InvestorID"), ldRowGrid("LinkID"))
                    End If
                End If
            Next
            ldtGridData.AcceptChanges()
            If menmSortingOn = SortingOn.Ascending Then
                ConductSorting("")
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            ldRowGrid = Nothing
            ldtGridData = Nothing
            Excel = Nothing
            llstLinkedFunds = Nothing
            grdData.ResumeRowSynchronization()
            grdData.EndUpdate()
        End Try
    End Sub

    Private Function GetEntityID() As Integer
        Dim lintEntityID As Integer
        Dim lobjData As CurrentDataSources
        lobjData = mstCurrentDataSources.Find(Function(p) p.AccessStatus = SourceAccessbility.Locked.ToString)
        If lobjData IsNot Nothing Then
            lintEntityID = lobjData.EntityID
        Else
            If mstCurrentDataSources IsNot Nothing Then
                If mstCurrentDataSources.Count > 1 Then
                    lintEntityID = mstCurrentDataSources(0).EntityID
                End If
            End If
        End If
        Return lintEntityID
    End Function

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub MakeNewFundRow(ByVal llstNewFundInvestor As AddNewInvestor, ByRef lDRow As DataRow)
        Dim lclsAddNewInvestor As New AddNewInvestor
        'grdData.EventManager.SetEnabled(Infragistics.Win.UltraWinGrid.GridEventIds.InitializeRow, False)
        Try
            lDRow("Activist") = llstNewFundInvestor.Activist
            lDRow("City") = llstNewFundInvestor.City
            lDRow("Country") = llstNewFundInvestor.Country
            lDRow("FundID") = llstNewFundInvestor.FundID
            lDRow("FundName") = llstNewFundInvestor.FundName
            lDRow("Head Investor") = llstNewFundInvestor.HeadInvestor
            lDRow("ID") = llstNewFundInvestor.ID
            lDRow("InvestorID") = llstNewFundInvestor.InvestorID
            lDRow("InvestorName") = llstNewFundInvestor.InvestorName
            lDRow("InvStatusCode") = llstNewFundInvestor.InvStatusCode
            lDRow("IsCutRow") = llstNewFundInvestor.IsCutRow
            lDRow("IsInvestor") = llstNewFundInvestor.IsInvestor
            lDRow("IsManaged") = llstNewFundInvestor.IsManaged
            lDRow("LinkID") = llstNewFundInvestor.LinkID
            lDRow("MInvestorTypeID") = llstNewFundInvestor.MInvestorTypeID
            lDRow("Name") = llstNewFundInvestor.Name
            lDRow("Notes") = llstNewFundInvestor.Notes
            lDRow("Origin") = llstNewFundInvestor.Origin
            lDRow("Parent") = llstNewFundInvestor.Parent
            lDRow("ProjectId") = llstNewFundInvestor.ProjectId
            lDRow("Region") = llstNewFundInvestor.Region
            lDRow("RowNumber") = llstNewFundInvestor.RowNumber
            lDRow("State") = llstNewFundInvestor.State
            lDRow("Style") = llstNewFundInvestor.Style
            lDRow("Turnover") = llstNewFundInvestor.Turnover
            lDRow("Type") = llstNewFundInvestor.Type
            lDRow("UserId") = llstNewFundInvestor.UserId
            lDRow("IsMasterDB") = llstNewFundInvestor.IsMasterDB
            lDRow("DenseRank") = llstNewFundInvestor.DenseRank
            lDRow("FundDenseRank") = llstNewFundInvestor.FundDenseRank
            lDRow("Status") = llstNewFundInvestor.Status
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            lclsAddNewInvestor = Nothing
            '   grdData.EventManager.SetEnabled(Infragistics.Win.UltraWinGrid.GridEventIds.InitializeRow, True)
        End Try
    End Sub
    ''' <summary>
    ''' Set the control properties.
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub DefaultSelectionOnNewInvestor()
        rdInvContains.Checked = True
        rdFundContains.Checked = True
        rdbCustomSearch.Checked = True
        chkSearchMasterDB.Checked = False
        rdbResults.Text = "Custom Search"
        rdbResults.Checked = True
    End Sub

    ''' <summary>
    ''' Retrive all the investors related to newly added fund.
    ''' </summary>
    ''' <param name="intFundID"></param>
    ''' <remarks></remarks>
    Private Sub AddInvestorsOfFund(ByVal intFundID As Integer)
        Dim ldtLinkedFunds As DataTable
        Dim ldtGridData As DataTable
        Dim ldRowGrid As DataRow
        Dim FilterQuery As String
        Dim Excel() As DataRow
        Dim llstLinkInvestors As List(Of AddNewInvestor)
        Dim lblnSaveData As Boolean = True
        Dim lintEntityId As Integer
        mstrInvestorNameSearch = String.Empty
        Try
            ldtGridData = New DataTable
            ldtLinkedFunds = New DataTable
            grdData.BeginUpdate()
            grdData.SuspendRowSynchronization()
            'Retrieve all the investor related to this fund.
            llstLinkInvestors = mclsDataHubManager.GetInvestorsOfFund(intFundID, mintProjectID, CommonCLL.UserID)
            lintEntityId = GetEntityID()
            ldtGridData = CType(grdData.DataSource, DataTable)
            'Check If Investor already exist in grid. than skip.don't add the investor to grid.
            For Each Investor As AddNewInvestor In llstLinkInvestors
                ldRowGrid = ldtGridData.NewRow()
                If Investor.IsInvestor Then
                    FilterQuery = "InvestorID ='" + Investor.InvestorID.ToString + "'"
                    Excel = ldtGridData.Select(FilterQuery)
                    'If investor not exist in grid than add to grid.
                    If Excel.Length = 0 Then
                        MakeNewFundRow(Investor, ldRowGrid)
                        ldtGridData.Rows.Add(ldRowGrid)
                        AddDataInSourceTracking(lintEntityId, ldRowGrid("InvestorID"), ldRowGrid("LinkID"))
                    End If
                Else
                    'Check the Combination of fund and Invesotr exist in grid.
                    FilterQuery = "InvestorID ='" + Investor.InvestorID.ToString + "' And FundID ='" + Investor.FundID.ToString + "'"
                    Excel = ldtGridData.Select(FilterQuery)
                    'If combination not exist than add to grid.
                    If Excel.Length = 0 Then
                        MakeNewFundRow(Investor, ldRowGrid)
                        ldtGridData.Rows.Add(ldRowGrid)
                        AddDataInSourceTracking(lintEntityId, ldRowGrid("InvestorID"), ldRowGrid("LinkID"))
                    End If
                End If
                If mstrInvestorNameSearch = String.Empty Then
                    mstrInvestorNameSearch = Investor.InvestorName
                Else
                    If Not mstrInvestorNameSearch.Contains(Investor.InvestorName) Then
                        mstrInvestorNameSearch = mstrInvestorNameSearch + mstrOROperator + Investor.InvestorName
                    End If
                End If
            Next
            ldtGridData.AcceptChanges()
            SaveData(lblnSaveData, False)
            If menmSortingOn = SortingOn.Ascending Then
                ConductSorting("")
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            ldRowGrid = Nothing
            ldtGridData = Nothing
            ldtLinkedFunds = Nothing
            Excel = Nothing
            grdData.ResumeRowSynchronization()
            grdData.EndUpdate()
        End Try
    End Sub

#End Region

#Region "Formula Calculatation"
    Public svalue As Integer = 0
    Dim toeval As String = New String("")
    Public inv As Integer = 0
    Dim prinv As Integer = 0
    Public prvAns As Number = New Number(0)
    Dim op As operation = operation.brc
    Dim op1, op2 As Number
    Dim Ieval As Short = 0
    Enum operation
        add
        mul
        div
        pow
        brc
    End Enum

    Private Property value As Object
    Friend WithEvents Expression As System.Windows.Forms.TextBox

    Private Function toint(ByVal a) As Integer
        Select Case (a)
            Case "1"c
                Return 1
            Case "2"c
                Return 2
            Case "3"c
                Return 3
            Case "4"c
                Return 4
            Case "5"c
                Return 5
            Case "6"c
                Return 6
            Case "7"c
                Return 7
            Case "8"c
                Return 8
            Case "9"c
                Return 9
        End Select
        Return 0
    End Function
    Private Sub atom(ByRef x As Number)
        x = 0
        Dim t As Integer = 1
        Dim t1 As Integer
        Dim xy As Number
        Dim sign As Integer = 1
        Dim y As Integer = 0

        If toeval(svalue) >= "0"c And toeval(svalue) <= "9"c Or toeval(svalue) = "."c Or toeval(svalue) = "i" Then
            While (toeval(svalue) >= "0"c And toeval(svalue) <= "9"c) OrElse toeval(svalue) = ","c
                If toeval(svalue) = ","c Then
                    svalue += 1
                    Continue While
                End If
                x = x * 10 + toint(toeval(svalue))
                svalue = svalue + 1
            End While
        Else
            If Not inv Then
                'Me.Value1.Text = "Invalid expression"
                inv = 1
            End If
            Return
        End If
        If toeval(svalue) = "." Then
            svalue = svalue + 1
            While toeval(svalue) >= "0"c And toeval(svalue) <= "9"c
                t1 = t
                xy = 1
                While Not t1 = 0
                    t1 = t1 - 1
                    xy = xy * 10
                End While
                x = x + toint(toeval(svalue)) / xy
                svalue = svalue + 1
                t = t + 1
            End While
        End If
        If toeval(svalue) = "E" Then
            svalue = svalue + 1
            While toeval(svalue) = "+" Or toeval(svalue) = "-"
                If toeval(svalue) = "-" Then
                    sign = sign * -1
                End If
                svalue = svalue + 1
            End While
            If toeval(svalue) >= "0"c And toeval(svalue) <= "9"c Or toeval(svalue) = "."c Then
                While toeval(svalue) >= "0"c And toeval(svalue) <= "9"c
                    y = y * 10 + toint(toeval(svalue))
                    svalue = svalue + 1
                End While
            Else
                If Not inv Then
                    'Me.Value1.Text = "Invalid expression"
                    inv = 1
                End If
                Return
            End If
            x = x * 10 ^ (sign * y)
        End If
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="x"></param>
    ''' <remarks></remarks>
    Private Sub eval5ba(ByRef x As Number)
        Dim temp As Number = x
        While eval5a() = 2
            temp = x
            eval5b(x, 0)
            x = temp * x
        End While
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="x"></param>
    ''' <param name="p"></param>
    ''' <remarks></remarks>
    Private Sub eval5b(ByRef x As Number, ByVal p As Boolean)
        If toeval.Length - svalue > 8 Then
            If toeval.Substring(svalue, 8) = "Infinity" Then
                x = 1 / 0
                svalue = svalue + 8
                'facto(x)
                If p Then
                    Return
                End If
                'power(x)
                eval5ba(x)
                Return
            End If
        End If
        If toeval.Length - svalue > 1 Then
            If toeval.Substring(svalue, 1) = "(" Then
                svalue = svalue + 1
                eval1(x)
                If Not toeval(svalue) = ")"c Then
                    toeval = toeval.Insert(svalue, ")")
                End If
                svalue = svalue + 1
                op = operation.brc
                If p Then
                    Return
                End If
            End If
        End If
    End Sub
    Private Function eval5a() As Integer
        If toeval.Length - svalue > 8 Then
            If toeval.Substring(svalue, 8) = "Infinity" Then
                Return 2
            End If
        End If
        If toeval.Length - svalue > 1 Then
            If toeval.Substring(svalue, 1) = "(" Then
                Return 1
            End If
        End If
        Return 0
    End Function

    Private Function eval5(ByRef x As Number) As Boolean
        If eval5a() = 0 Then
            Return False
        End If
        eval5b(x, 0)
        While eval5a() >= 1
            Dim temp1 As Number = x
            eval5b(x, 0)
            x = x * temp1
        End While
        Return True
    End Function

    Private Sub eval4(ByRef x As Number)
        If eval5(x) Then
            Return
        End If
        atom(x)
        Dim temp As Number
        temp = x
        If eval5(x) Then
            x = x * temp
        End If
    End Sub
    Private Sub eval3a(ByRef x As Number)
        Dim a As Char
        a = toeval(svalue)
        If Equals(a, "+"c) Or Equals(a, "-"c) Then
            svalue = svalue + 1
            eval3a(x)
        Else
            eval4(x)
        End If
        If a = "-"c Then
            x = -x
        End If
    End Sub

    Public Sub eval3(ByRef x As Number)
        Dim temp As Number = New Number
        eval3a(x)
    End Sub

    Private Sub eval2(ByRef x As Number)
        Dim temp As Number = New Number
        Dim a As Char
        eval3(x)
        While Equals(toeval(svalue), "*"c) Or Equals(toeval(svalue), "/"c) Or 0 >= svalue + 3
            If Not (Equals(toeval(svalue), "*"c) Or Equals(toeval(svalue), "/"c)) Then
                If Not Equals(toeval.Substring(svalue, 3), "mod") Then
                    Return
                End If
            End If
            a = toeval(svalue)
            If a = "m"c Then
                svalue = svalue + 2
            End If
            svalue = svalue + 1
            eval3(temp)
            If a = "*"c Then
                x = x * temp
                op = operation.mul
            ElseIf a = "/"c Then
                x = x / temp
                op = operation.div
            End If
        End While
    End Sub

    Private Sub eval1(ByRef x As Number)
        Dim temp As Number = New Number
        Dim a As Char
        eval2(x)
        While Equals(toeval(svalue), "+"c) Or Equals(toeval(svalue), "-"c)
            a = toeval(svalue)
            svalue = svalue + 1
            eval2(temp)
            If a = "+"c Then
                x = x + temp
            ElseIf a = "-"c Then
                x = x - temp
            End If
            op = operation.add
            op2 = temp
        End While
    End Sub
#End Region

#Region "Cut And Insert Operations"
    ''' <summary>
    ''' Implements the cut operation
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub PerformCutOperation()
        'If any Investor row is selected, then exit as only Funds are allowed for Cut operation
        If CheckIfAnyInvestorSelected() = False Then Exit Sub
        Dim lintRowCounter As Integer = 0
        Dim lblnESourceValue As Boolean = False
        Dim lintColCounter As Integer = 0
        Dim lobjCurrentDataSources As CurrentDataSources = Nothing
        Dim lintCutRowCounter As Integer = 0
        Try
            mblnIsCutOperationInProgress = True
            If marrCutRows Is Nothing Then
                lintCutRowCounter = marrCutRows.Count
            End If
            'Traverse all the selected fund rows
            For Each lUltraRow As UltraGridRow In grdData.Selected.Rows
                lintColCounter = 0
                'If an eSource value fund is selected then inform the user to unmap it from the eSource Mapping screen first.
                While lintColCounter < mstCurrentDataSources.Count
                    lobjCurrentDataSources = mstCurrentDataSources(lintColCounter)
                    If mstESourceType.Contains(lobjCurrentDataSources.SourceTypeCode) Then
                        If lUltraRow.GetCellValue(lobjCurrentDataSources.SourceName).ToString.Equals("") = False Then
                            lblnESourceValue = True
                            Continue For
                        End If
                    End If
                    lintColCounter += 1
                End While
                lintRowCounter = 0
                If marrCutRows Is Nothing Then
                    marrCutRows = New List(Of UltraGridRow)
                End If
                While lintRowCounter < marrCutRows.Count
                    If marrCutRows(lintRowCounter) Is Nothing Then
                        lintRowCounter += 1
                        Continue While
                    End If
                    If marrCutRows(lintRowCounter).GetCellValue("LinkID") = lUltraRow.GetCellValue("LinkID") Then Continue For
                    lintRowCounter += 1
                End While
                'Mark the row as a CutRow
                lUltraRow.Cells("IsCutRow").Value = True
                marrCutRows.Add(lUltraRow)
                'Change the backcolor as well
                lUltraRow.Appearance.BackColor = grdData.DisplayLayout.Appearances("CutRowBackColor").BackColor '. Color.FromArgb(242, 225, 229)
            Next

            'If an eSource value fund is selected then inform the user to unmap it from the eSource Mapping screen first.
            If lblnESourceValue Then
                If marrCutRows.Count = lintCutRowCounter + grdData.Selected.Rows.Count - 1 Then
                    Me.ShowMessageBox(DBResult.DE_CUT_ESOURCE_VALUE_SINGLE)
                Else
                    Me.ShowMessageBox(DBResult.DE_CUT_ESOURCE_VALUE_MULTIPLE)
                End If
            End If

            'Recalculate Investor and Managed Fund Positions for the Cut rows
            'SetInvAndManagedFundPositionsForCut(False, Nothing)
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, 0)
        Finally
            lobjCurrentDataSources = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' To add a row in data source tracking table which will be used in Save Process
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub AddDataInSourceTracking(ByVal pintEntityID As Integer, ByVal pintInvestorID As Integer, ByVal pintLinkID As Integer)
        Dim lobjDataChanges As DataSourceChanges = Nothing
        Try
            lobjDataChanges = New DataSourceChanges
            'lobjDataChanges.ListingID = pintListingID
            lobjDataChanges.EntityID = pintEntityID
            lobjDataChanges.InvestorID = pintInvestorID
            'lobjDataChanges.FundID = pintFundID
            lobjDataChanges.LinkID = pintLinkID
            lobjDataChanges.Position = 0
            lobjDataChanges.SourceDate = Nothing
            lobjDataChanges.IsSumOfFunds = True
            lobjDataChanges.Formula = ""
            mstDataSourceChanges.Add(lobjDataChanges)
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, 0)
        Finally
            lobjDataChanges = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' To update the change tracking tables which are used in Save Process
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub UpdateChangeTrackingTablesForChangeFund(ByVal pintOldLinkID As Integer, ByVal pintNewInvestorID As Integer, ByVal pintNewLinkID As Integer, ByVal pintNewFundID As Integer)
        Dim lobjLinkingChanges As LinkingChanges
        Try
            For Each lobjDataSourceChanges As DataSourceChanges In mstDataSourceChanges
                If pintOldLinkID = lobjDataSourceChanges.LinkID Then
                    lobjDataSourceChanges.InvestorID = pintNewInvestorID
                    lobjDataSourceChanges.LinkID = pintNewLinkID
                End If
            Next

            'Update the changes tracking tables with new InvestorID and LinkID for previous project changes
            For Each lobjPreviousProjectChanges As FLPositionChanges In mstPreviousProjectChanges
                If pintOldLinkID = lobjPreviousProjectChanges.LinkID Then
                    lobjPreviousProjectChanges.InvestorID = pintNewInvestorID
                    lobjPreviousProjectChanges.LinkID = pintNewLinkID
                End If
            Next
            'ldrChangedRow = mdtLinkingChanges.Rows.Find(New Object() {lurMovingRow.GetCellValue(lurMovingRow.Cells("LinkID").Column), ldrLinkingRow(lstrNewLinkIDCol)})
            lobjLinkingChanges = mstLinkingChanges.Find(Function(p) p.OldLinkID = pintOldLinkID And p.NewFundID = pintNewFundID)

            'Update the changes tracking tables with NewLinkID
            If lobjLinkingChanges Is Nothing Then
                lobjLinkingChanges = New LinkingChanges
                lobjLinkingChanges.OldLinkID = pintOldLinkID
                lobjLinkingChanges.NewLinkID = pintNewLinkID
                lobjLinkingChanges.NewFundID = pintNewFundID
                mstLinkingChanges.Add(lobjLinkingChanges)
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, 0)
        Finally
            lobjLinkingChanges = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' Implements the Insert operation
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub PerformInsertOperation()
        Dim lstInvAndFundIDs As New List(Of LinkingDetails)
        Dim lobjInvAndFundIDs As LinkingDetails = Nothing
        Dim lserInvAndFundIDs As New System.Xml.Serialization.XmlSerializer(GetType(List(Of LinkingDetails)))
        Dim lurMovingRow As UltraGridRow = Nothing
        Dim ldtCurrentData As DataTable = grdData.DataSource
        Dim lstrExistingFunds As New StringBuilder
        Dim lstLinkings As IList(Of LinkingDetails)
        Dim lintActiveRowIndex As Integer
        Dim lintNewInvestorID As Integer
        Dim lintCutRowCounter As Integer
        Dim lobjLinkingRow As LinkingDetails = Nothing
        Dim lintMovingRowNewIndex As Integer
        Dim lobjLinkingChanges As LinkingChanges
        Dim lobjChangedLinking As LinkingChanges
        Dim ldtSourceSOFStatus As DataTable = Nothing
        Dim ldtFLSOFStatus As DataTable = Nothing
        Dim lstNonPivotCols As New List(Of String)
        Dim lstPivotCols As New List(Of String)
        Dim ldrAssociatedRow As DataRow = Nothing
        Dim lblnCanGoAhead As Boolean = True
        Dim lugrCurrentRow As UltraGridRow = Nothing
        grdData.BeginUpdate()
        grdData.SuspendRowSynchronization()
        Try
            If grdData.ActiveRow Is Nothing Then Exit Sub
            If marrCutRows.Count = 0 Then Exit Sub

            'Start adding rows from row next to the currently selected row
            lintActiveRowIndex = grdData.ActiveRow.Index + 1
            If grdData.ActiveRow.GetCellValue("LinkID") = 0 Then
                lugrCurrentRow = grdData.Rows(grdData.ActiveRow.Index - 1)
            Else
                lugrCurrentRow = grdData.ActiveRow
            End If
            lintNewInvestorID = lugrCurrentRow.GetCellValue("InvestorID")
            'Start adding the rows in reverse order in datatable
            marrCutRows.Reverse()
            lintCutRowCounter = marrCutRows.Count - 1
            'If a fund already exists under the selected investor, then don't move it and inform the user
            While lintCutRowCounter >= 0
                Dim ldr As DataRow = ldtCurrentData.Rows.Find(New Object() {lintNewInvestorID, marrCutRows(lintCutRowCounter).GetCellValue("FundID")})

                If ldtCurrentData.Rows.Find(New Object() {lintNewInvestorID, marrCutRows(lintCutRowCounter).GetCellValue("FundID")}) IsNot Nothing Then
                    lstrExistingFunds.Append(marrCutRows(lintCutRowCounter).GetCellValue("FundName")).Append(", ")
                    marrCutRows(lintCutRowCounter).Appearance.BackColor = grdData.DisplayLayout.Appearances("CancelCutRowBackColor").BackColor 'mclrGridFundBackColor
                    marrCutRows.Remove(marrCutRows(lintCutRowCounter))
                    lintCutRowCounter -= 1
                    Continue While
                End If
                lobjInvAndFundIDs = New LinkingDetails
                lobjInvAndFundIDs.InvestorID = lintNewInvestorID
                lobjInvAndFundIDs.FundID = marrCutRows(lintCutRowCounter).GetCellValue("FundID")
                lstInvAndFundIDs.Add(lobjInvAndFundIDs)
                lintCutRowCounter -= 1
            End While
            If lstrExistingFunds.Length > 0 Then
                If lstrExistingFunds.Length > 0 Then
                    lstrExistingFunds.Length = lstrExistingFunds.Length - 2
                End If
                MessageBox.Show("Following fund(s) cannot be moved as these are already linked with the selected investor." + Environment.NewLine + lstrExistingFunds.ToString, CommonCLL.mstrMsgBoxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information)
                If marrCutRows.Count = 0 Then
                    marrCutRows = New List(Of UltraGridRow)
                    Exit Sub
                End If
            End If
            For Each lUltraRow As UltraGridRow In marrCutRows
                If ldtCurrentData.Rows.Find(New Object() {lintNewInvestorID, lUltraRow.GetCellValue("FundID")}) IsNot Nothing Then
                    lstrExistingFunds.Append(lUltraRow.GetCellValue("FundName")).Append(", ")
                    marrCutRows.Remove(lUltraRow)
                    Continue For
                End If
            Next
            'To keep the list in its original sequence again
            marrCutRows.Reverse()

            'Recalculate Investor and Managed Fund Positions for the Cut rows
            SetInvAndManagedFundPositionsForCut(False, Nothing)

            lstLinkings = mclsDataHubManager.GetLinking(SerializeFromObject(lserInvAndFundIDs, System.Text.Encoding.UTF8, lstInvAndFundIDs))
            'If its from Recall, then Get the linking information of the Investors and Funds
            lintCutRowCounter = marrCutRows.Count - 1
            lintMovingRowNewIndex = lintActiveRowIndex

            'To move the rows from one place to another
            While lintCutRowCounter >= 0
                lurMovingRow = marrCutRows(lintCutRowCounter)
                lobjLinkingRow = lstLinkings.Item(lintCutRowCounter)
                'Update the changes tracking tables with new InvestorID and LinkID for data source changes
                UpdateChangeTrackingTablesForChangeFund(lurMovingRow.GetCellValue("LinkID"), lintNewInvestorID, lobjLinkingRow.LinkID, lobjLinkingRow.FundID)

                If lurMovingRow.Index < lintActiveRowIndex Then
                    If lintCutRowCounter = marrCutRows.Count - 1 Then
                        lintMovingRowNewIndex = lintActiveRowIndex - 2
                    Else
                        lintMovingRowNewIndex -= 1
                    End If
                Else
                    If lintCutRowCounter = marrCutRows.Count - 1 Then
                        lintMovingRowNewIndex -= 1
                    End If
                End If
                'Move the row location and change the backcolor to normal
                grdData.Rows.Move(lurMovingRow, lintMovingRowNewIndex)
                lurMovingRow.Appearance.BackColor = grdData.DisplayLayout.Appearances("CancelCutRowBackColor").BackColor 'mclrGridFundBackColor

                'Set the IsCutRow status to true, so that such rows can be excluded while calculating Investor's/Managed Fund's positions.
                'Update the position values of the investor from which rows are being cut.
                lurMovingRow.Cells("IsCutRow").Value = False
                lintCutRowCounter -= 1
            End While

            lstNonPivotCols.Add("InvestorID")
            lstNonPivotCols.Add("FundID")
            lstPivotCols.Add(mstrSOFColPrefix)
            lstPivotCols.Add(mstrFormulaColSuffix.Trim)
            'lstPivotCols.Add("Position")
            mclsDataHubManager.GetSourceSOFStatus(mintProjectID, String.Join(",", lstInvAndFundIDs.Select(Function(lobjLinking) lobjLinking.InvestorID)).ToString, _
                                                      lstNonPivotCols, lstPivotCols, mstrPreviousProjectName, ldtSourceSOFStatus, ldtFLSOFStatus, mintClientID)
            If mdtDEAssociatedData Is Nothing Then
                mdtDEAssociatedData = New DataTable
            End If
            If mdtFLAssociatedData Is Nothing Then
                mdtFLAssociatedData = New DataTable
            End If
            mdtDEAssociatedData.Merge(ldtSourceSOFStatus, True, MissingSchemaAction.Add)
            mdtFLAssociatedData.Merge(ldtFLSOFStatus, True, MissingSchemaAction.Add)
            SetPrimaryKey(mdtDEAssociatedData)
            SetPrimaryKey(mdtFLAssociatedData)
            'Recalculate Investor and Managed Fund Positions for the Cut rows
            SetInvAndManagedFundPositionsForCut(True, lurMovingRow)
            'Save the data into the database immediately after Insert operation

            SaveData(lblnCanGoAhead, False)

            If lblnCanGoAhead Then
                lintCutRowCounter = marrCutRows.Count - 1
                While lintCutRowCounter >= 0
                    lurMovingRow = marrCutRows(lintCutRowCounter)
                    If mdtDEAssociatedData IsNot Nothing Then
                        If mdtDEAssociatedData.Rows.Count > 0 Then
                            ldrAssociatedRow = Nothing
                            ldrAssociatedRow = mdtDEAssociatedData.Rows.Find(New Object() {lurMovingRow.GetCellValue("InvestorID"), lurMovingRow.GetCellValue("FundID")})
                            If ldrAssociatedRow IsNot Nothing Then
                                mdtDEAssociatedData.Rows.Remove(ldrAssociatedRow)
                            End If
                        End If
                    End If
                    If mdtFLAssociatedData IsNot Nothing Then
                        If mdtFLAssociatedData.Rows.Count > 0 Then
                            ldrAssociatedRow = Nothing
                            ldrAssociatedRow = mdtFLAssociatedData.Rows.Find(New Object() {lurMovingRow.GetCellValue("InvestorID"), lurMovingRow.GetCellValue("FundID")})
                            If ldrAssociatedRow IsNot Nothing Then
                                mdtFLAssociatedData.Rows.Remove(ldrAssociatedRow)
                            End If
                        End If
                    End If
                    lobjLinkingRow = lstLinkings.Item(lintCutRowCounter)
                    'Update the rows with the new InvestorID and LinkID
                    lurMovingRow.Cells("InvestorID").Value = lintNewInvestorID
                    lurMovingRow.Cells("LinkID").Value = lobjLinkingRow.LinkID
                    lurMovingRow.Cells("InvestorName").Value = lugrCurrentRow.GetCellValue("InvestorName")
                    lurMovingRow.Cells("DenseRank").Value = lugrCurrentRow.GetCellValue("DenseRank")
                    lintCutRowCounter -= 1
                End While
            End If
            marrCutRows = New List(Of UltraGridRow)
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, 0)
        Finally
            grdData.EndUpdate()
            grdData.ResumeRowSynchronization()
            grdData.UpdateData()
            ldrAssociatedRow = Nothing
            lstPivotCols = Nothing
            lstNonPivotCols = Nothing
            lstInvAndFundIDs = Nothing
            lstLinkings = Nothing
            lstrExistingFunds = Nothing
            lobjInvAndFundIDs = Nothing
            lurMovingRow = Nothing
            ldtCurrentData = Nothing
            ldtFLSOFStatus = Nothing
            lobjLinkingRow = Nothing
            lobjLinkingChanges = Nothing
            lobjChangedLinking = Nothing
            ldtSourceSOFStatus = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' To set the Investor and Managed Fund's positions for Cut rows
    ''' </summary>
    ''' <param name="pblnIsRecall"></param>
    ''' <param name="lurReplacedRow"></param>
    ''' <remarks></remarks>
    Private Sub SetInvAndManagedFundPositionsForCut(ByVal pblnIsRecall As Boolean, ByVal lurReplacedRow As UltraGridRow)
        Dim lstHandledInvestors As New List(Of Integer)
        Try
            If pblnIsRecall Then
                'It will run only on one row, the given row
                'Update the Investor and Managed fund positions accordingly for current data sources
                For Each lobjCurrentDataSources As CurrentDataSources In mstCurrentDataSources
                    If marrToplineNeverSOF.Contains(lobjCurrentDataSources.SourceTypeCode) Then Continue For
                    CalculateInvAndManagedFundPositions(InvestorPositionSources.OnCellChange, True, lurReplacedRow.Cells(lobjCurrentDataSources.SourceName))
                Next
                'Update the Investor and Managed fund positions accordingly for previous projects
                For Each lobjPreviousProjects As PreviousProjects In mstPreviousProjects
                    CalculateInvAndManagedFundPositions(InvestorPositionSources.OnCellChange, False, lurReplacedRow.Cells(lobjPreviousProjects.DeliveryListing))
                Next
                If menmScreenType = DataHubScreenType.FinalizeList Then
                    'Update the Investor and Managed fund positions accordingly for current listings
                    For Each lobjListingInformation As ListingInformation In mstListingInformation
                        CalculateInvAndManagedFundPositions(InvestorPositionSources.OnCellChange, False, lurReplacedRow.Cells(lobjListingInformation.CurrentListingName))
                    Next
                End If
            Else
                'Set the IsCutRow status to true, so that such rows can be excluded while calculating Investor's/Managed Fund's positions.
                'Update the position values of the investor from which rows are being cut.
                'It'll run on all Cut rows
                For Each lUltrarow As UltraGridRow In marrCutRows
                    If lUltrarow IsNot Nothing Then
                        If lstHandledInvestors.Contains(lUltrarow.GetCellValue(lUltrarow.Cells("InvestorID").Column)) Then Continue For
                        lstHandledInvestors.Add(lUltrarow.GetCellValue(lUltrarow.Cells("InvestorID").Column))
                        'Update the Investor and Managed fund positions accordingly for current data sources
                        For Each lobjCurrentDataSources As CurrentDataSources In mstCurrentDataSources
                            If marrToplineNeverSOF.Contains(lobjCurrentDataSources.SourceTypeCode) OrElse lUltrarow.GetCellValue(lobjCurrentDataSources.SourceName).ToString.Equals("") _
                                OrElse lUltrarow.GetCellValue(lobjCurrentDataSources.SourceName).ToString.Equals(mstrNDValue) Then Continue For
                            CalculateInvAndManagedFundPositions(InvestorPositionSources.OnCellChange, True, lUltrarow.Cells(lobjCurrentDataSources.SourceName))
                        Next
                        'Update the Investor and Managed fund positions accordingly for previous projects
                        For Each lobjPreviousProjects As PreviousProjects In mstPreviousProjects
                            If lUltrarow.GetCellValue(lobjPreviousProjects.DeliveryListing).ToString.Equals("") _
                                OrElse lUltrarow.GetCellValue(lobjPreviousProjects.DeliveryListing).ToString.Equals(mstrNDValue) Then Continue For
                            CalculateInvAndManagedFundPositions(InvestorPositionSources.OnCellChange, False, lUltrarow.Cells(lobjPreviousProjects.DeliveryListing))
                        Next

                        If menmScreenType = DataHubScreenType.FinalizeList Then
                            'Update the Investor and Managed fund positions accordingly for current listings
                            For Each lobjListingInformation As ListingInformation In mstListingInformation
                                If lUltrarow.GetCellValue(lobjListingInformation.CurrentListingName).ToString.Equals("") _
                                OrElse lUltrarow.GetCellValue(lobjListingInformation.CurrentListingName).ToString.Equals(mstrNDValue) Then Continue For
                                CalculateInvAndManagedFundPositions(InvestorPositionSources.OnCellChange, False, lUltrarow.Cells(lobjListingInformation.CurrentListingName))
                            Next
                        End If
                    End If
                Next
                lstHandledInvestors = Nothing
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            lstHandledInvestors = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' To cancel out the Cut operations
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub CancelOutCutOperation()
        'If there are any Cut rows then set their color back to Normal and set its IsCutRow status to false
        Try
            If marrCutRows Is Nothing Then Exit Sub
            If marrCutRows.Count >= 1 AndAlso marrCutRows(0) IsNot Nothing Then
                'Set the cut row status of the row to false
                For Each lUltrarow As UltraGridRow In marrCutRows
                    If lUltrarow IsNot Nothing Then
                        lUltrarow.Cells("IsCutRow").Value = False
                        lUltrarow.Appearance.BackColor = grdData.DisplayLayout.Appearances("FundRowBackColor").BackColor
                    End If
                Next
                'Recalculate Investor's and Managed Fund's position
                'SetInvAndManagedFundPositionsForCut(False, Nothing)
                'Clear and resize the cut row arry
                marrCutRows = New List(Of UltraGridRow)
                mblnIsCutOperationInProgress = False
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
        End Try
    End Sub

    ''' <summary>
    ''' To check if any Investor row is selected
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function CheckIfAnyInvestorSelected() As Boolean
        For Each lUltraRow As UltraGridRow In grdData.Selected.Rows
            If lUltraRow.GetCellValue("LinkID") = 0 Then Return False
        Next
        Return True
    End Function

#End Region

#Region "Lock/Unlock Functionality"
    ''' <summary>
    ''' Procedure to call save data and lock/unlock functionality
    ''' </summary>
    ''' <param name="pblnCanGetLockedColDirectly"></param>
    ''' <param name="pblnSkipSave"></param>
    ''' <remarks></remarks>
    Private Sub CallUnlockFunctionality(ByVal pblnCanGetLockedColDirectly As Boolean, ByVal pblnSkipSave As Boolean, ByRef pblnCanGoAhead As Boolean)
        If pblnSkipSave = False Then
            SaveData(pblnCanGoAhead, False)
        End If
        If pblnCanGoAhead AndAlso menmScreenType = DataHubScreenType.DataEntry Then
            LockUnlockEntities(False, pblnCanGetLockedColDirectly)
        End If
    End Sub

    ''' <summary>
    ''' To lock unlock the data sources
    ''' </summary>
    ''' <param name="pblnIsLock"></param>
    ''' <param name="pblnCanGetLockedColDirectly"></param>
    ''' <remarks></remarks>
    Private Sub LockUnlockEntities(ByVal pblnIsLock As Boolean, ByVal pblnCanGetLockedColDirectly As Boolean)
        'If there is no data source right clicked, then exit
        If mstrRightClickColName.Equals("") Then Exit Sub
        Dim enmResult As DBResult
        Dim lstrErrorMessage As String = ""
        Dim lobjCurrentAllDataSources As List(Of CurrentDataSources) = Nothing
        Dim lstrUserFullName As String = ""
        Dim lstrSelectedEntities As StringBuilder
        Dim lstrSelectedDataEntities As StringBuilder
        Dim lintLastUserID As Integer = 0
        Dim lstLockingCol As IList(Of DataEntities) = Nothing
        Dim lobjLockingCol As DataEntities = Nothing
        Dim lstActiveDataSources As New List(Of CurrentDataSources)
        Dim lobjDataSourceStatus As SourceEntityAccessStatus = Nothing
        Dim lstrSourceFirstName As String
        Dim lserDataEntities As New System.Xml.Serialization.XmlSerializer(GetType(List(Of DataEntities)))
        Dim lSourceAccessbility As SourceAccessbility
        Dim lblnShouldReSort As Boolean
        Try
            'To store the data sources names to be locked
            lstrSelectedDataEntities = New StringBuilder
            'To store the data sources EntityID's to be locked
            lstrSelectedEntities = New StringBuilder
            lstLockingCol = New List(Of DataEntities)
            ''Get the status of the data sources being asked
            'lstDataSourceStatus = mclsDataHubManager.GetAccessDataSourceStatus(mintProjectID, CommonCLL.UserID)
            ''If there is any data source which is already locked by some other user, then inform the user about it
            If pblnCanGetLockedColDirectly Then
                CallUnlockFunctionality(True, False, True)
            Else
                'Find the data source column being locked
                If pblnIsLock Then
                    lobjCurrentAllDataSources = mstCurrentDataSources.FindAll(Function(p) p.SourceName = mstrRightClickColName)
                    If lobjCurrentAllDataSources.Count = 0 Then
                        lobjCurrentAllDataSources = mstCurrentDataSources.FindAll(Function(p) p.SourceDate = mstrRightClickColName)
                    End If
                Else
                    lobjCurrentAllDataSources = mstCurrentDataSources.FindAll(Function(p) p.AccessStatus = SourceAccessbility.Locked.ToString)
                End If
                'lobjCurrentDataSources = mstCurrentDataSources.Find(Function(p) p.SourceName = mstrRightClickColName)
                If lobjCurrentAllDataSources.Count = 0 Then Exit Sub
                'If it's an Update then lock all the updates column
                For Each lobjCurrentDataSources As CurrentDataSources In lobjCurrentAllDataSources
                    If lobjCurrentDataSources.SourceTypeCode = SourceTypeCode.UPD.ToString Then
                        lstrSourceFirstName = lobjCurrentDataSources.SourceName.Substring(0, lobjCurrentDataSources.SourceName.Length - lobjCurrentDataSources.ListingName.Length)
                        For Each lobjDataSources As CurrentDataSources In mstCurrentDataSources
                            If lobjDataSources.SourceName = lstrSourceFirstName + lobjDataSources.ListingName Then
                                lobjLockingCol = New DataEntities
                                lobjLockingCol.EntityID = lobjDataSources.EntityID
                                lobjLockingCol.SourceName = lobjDataSources.SourceName
                                lstActiveDataSources.Add(lobjDataSources)
                                lstLockingCol.Add(lobjLockingCol)
                                lstrSelectedEntities.Append(lobjDataSources.EntityID.ToString)
                                lstrSelectedEntities.Append(",")
                                lstrSelectedDataEntities.Append(lobjDataSources.SourceName)
                                lstrSelectedDataEntities.Append(",")
                            End If
                        Next
                        'Otherwise lock only the requested column
                    Else
                        lstActiveDataSources.Add(lobjCurrentDataSources)
                        lstrSelectedEntities.Append(lobjCurrentDataSources.EntityID.ToString).Append(",")
                        lstrSelectedDataEntities.Append(lobjCurrentDataSources.SourceName + ",")
                        lobjLockingCol = New DataEntities
                        lobjLockingCol.EntityID = lobjCurrentDataSources.EntityID
                        lobjLockingCol.SourceName = lobjCurrentDataSources.SourceName
                        lstLockingCol.Add(lobjLockingCol)
                    End If
                Next
            End If
            If lstrSelectedEntities.Length > 0 Then
                lstrSelectedEntities.Length = lstrSelectedEntities.Length - 1
            End If

            If lstrSelectedDataEntities.Length > 0 Then
                lstrSelectedDataEntities.Length = lstrSelectedDataEntities.Length - 1
            End If

            'Lock the requested columns
            mclsDataHubManager.AccessDataSource(SerializeFromObject(lserDataEntities, System.Text.Encoding.UTF8, lstLockingCol), pblnIsLock, enmResult, lstrErrorMessage, _
                                                lstrUserFullName, lintLastUserID)
            If enmResult = DBResult.SUCCESS OrElse enmResult = DBResult.DE_ENTIY_DETLS_CHNGD Then
                'Once locked, cancel out any pending Cut operation
                CancelOutCutOperation()
                'If there is any change in the column name/details, inform the user.
                If enmResult = DBResult.DE_ENTIY_DETLS_CHNGD Then
                    Me.ShowMessageBox(DBResult.DE_ENTIY_DETLS_CHNGD)
                End If
                If pblnIsLock Then
                    lSourceAccessbility = SourceAccessbility.Locked
                    'Do the row level changes, recall the changes from DB
                    lblnShouldReSort = False
                    RecallDataChanges(lblnShouldReSort)
                    'Conduct the sorting if required
                    If lblnShouldReSort Then
                        ConductSorting("")
                    End If

                    'GetLockedEntityUpdatedData(lstrSelectedEntities.ToString, lstrSelectedDataEntities.ToString, lstActiveDataSources)

                    'Recall the column level changes and update the grid
                    If lintLastUserID = CommonCLL.UserID Then
                        GetUpdatedDataForSOFFormula(lstrSelectedEntities.ToString, lstrSelectedDataEntities.ToString, lstActiveDataSources)
                    Else
                        GetLockedEntityUpdatedData(lstrSelectedEntities.ToString, lstrSelectedDataEntities.ToString, lstActiveDataSources, True, False)
                    End If
                    'Fetch the updated status of Doubt of each data source
                    GetEntityDoubtStatus(lstrSelectedEntities.ToString)
                Else
                    lSourceAccessbility = SourceAccessbility.Unlocked
                End If

                If pblnIsLock Then
                    lobjCurrentAllDataSources = mstCurrentDataSources.FindAll(Function(p) p.SourceName = mstrRightClickColName)
                    If lobjCurrentAllDataSources.Count = 0 Then
                        lobjCurrentAllDataSources = mstCurrentDataSources.FindAll(Function(p) p.SourceDate = mstrRightClickColName)
                    End If
                Else
                    lobjCurrentAllDataSources = mstCurrentDataSources.FindAll(Function(p) p.AccessStatus = SourceAccessbility.Locked.ToString)
                End If
                'If the column being locked is an UPDATE, then set the status of all update colummns to lock
                For Each lobjCurrentDataSources As CurrentDataSources In lobjCurrentAllDataSources
                    If lobjCurrentDataSources.SourceTypeCode = SourceTypeCode.UPD.ToString Then
                        lstrSourceFirstName = lobjCurrentDataSources.SourceName.Substring(0, lobjCurrentDataSources.SourceName.Length - lobjCurrentDataSources.ListingName.Length)
                        For Each lobjDataSources As CurrentDataSources In mstCurrentDataSources
                            If lobjDataSources.SourceName = lstrSourceFirstName + lobjDataSources.ListingName Then
                                lobjDataSources.AccessStatus = lSourceAccessbility.ToString
                            End If
                        Next
                    Else
                        'Otherwise set the status for the given column
                        lobjCurrentDataSources.AccessStatus = lSourceAccessbility.ToString
                    End If
                Next
                ''Set the visible position of the locked column to be the immediate Next column of Name column
                SetVisiblePosition(pblnIsLock)
                'Inform the user if it's already in use by someone
            ElseIf enmResult = DBResult.DE_ENTITY_IN_USE Then
                Me.ShowMessageBox(DBResult.DE_ENTITY_IN_USE, lstrUserFullName)
            ElseIf enmResult = DBResult.DE_ENTIY_NOT_EXISTS Then
                'If the data source does not exist anymore, then delete it from the grid
                Me.ShowMessageBox(DBResult.DE_ENTIY_NOT_EXISTS)
                DeleteDataEntityFromFrontEnd(lstrSelectedDataEntities.ToString, grdData.DataSource)
            Else
                Me.ShowMessageBox(enmResult)
            End If
            grdData.UpdateData()
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            lstrSelectedEntities = Nothing
            lstrSelectedDataEntities = Nothing
            lstActiveDataSources = Nothing
            lstLockingCol = Nothing
            lobjCurrentAllDataSources = Nothing
            lobjLockingCol = Nothing
            lobjDataSourceStatus = Nothing
            lserDataEntities = Nothing
            lSourceAccessbility = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' Set the visible position of the data source and associated date column
    ''' </summary>
    ''' <param name="pblnIsLocked"></param>
    ''' <remarks></remarks>
    Private Sub SetVisiblePosition(ByVal pblnIsLocked As Boolean)
        Dim lstrSourceDateCol As String = ""
        Dim lintRowCounter As Integer = mstCurrentDataSources.Count - 1
        Dim lintSourceColCount As Integer = 0
        Dim lobjTop1DataSources As CurrentDataSources = Nothing
        Dim lstrResearchSource As String = ""
        'If its lock functionality
        If pblnIsLocked Then
            While lintRowCounter >= 0
                'Implement the following on each locked column
                If mstCurrentDataSources.Item(lintRowCounter).AccessStatus = SourceAccessbility.Locked.ToString Then
                    If lobjTop1DataSources Is Nothing Then
                        lobjTop1DataSources = mstCurrentDataSources.Item(lintRowCounter)
                    End If
                    lintSourceColCount += 1
                    'Set the backcolor, visible position, allow edit of data source and date column
                    grdData.Rows.Band.Columns(mstCurrentDataSources.Item(lintRowCounter).SourceName).CellAppearance.BackColor = grdData.DisplayLayout.Appearances("VisiblePosition").BackColor 'VisiblePosition Color.FromArgb(201, 217, 233)
                    grdData.Rows.Band.Columns(mstCurrentDataSources.Item(lintRowCounter).SourceName).Header.VisiblePosition = grdData.Rows.Band.Columns("Parent").Header.VisiblePosition + 1
                    grdData.Rows.Band.Columns(mstCurrentDataSources.Item(lintRowCounter).SourceName).CellActivation = Activation.AllowEdit
                    If mstAllDataSourceDateCols.Contains(mstCurrentDataSources.Item(lintRowCounter).SourceName + mstrSourceDateColSuffix) Then
                        lintSourceColCount += 1
                        grdData.Rows.Band.Columns(mstCurrentDataSources.Item(lintRowCounter).SourceName + mstrSourceDateColSuffix).Header.VisiblePosition = grdData.Rows.Band.Columns(mstCurrentDataSources.Item(lintRowCounter).SourceName).Header.VisiblePosition + 1
                        grdData.Rows.Band.Columns(mstCurrentDataSources.Item(lintRowCounter).SourceName + mstrSourceDateColSuffix).CellAppearance.BackColor = grdData.DisplayLayout.Appearances("VisiblePosition").BackColor
                        grdData.Rows.Band.Columns(mstCurrentDataSources.Item(lintRowCounter).SourceName + mstrSourceDateColSuffix).CellActivation = Activation.AllowEdit
                    End If
                    If lobjTop1DataSources.ResearchSourceCol IsNot Nothing Then
                        If lobjTop1DataSources.ResearchSourceCol.ToString.Equals("") = False Then
                            lintSourceColCount += 1
                            grdData.Rows.Band.Columns(lobjTop1DataSources.ResearchSourceCol).Header.VisiblePosition = grdData.Rows.Band.Columns(mstCurrentDataSources.Item(lintRowCounter).SourceDate).Header.VisiblePosition + 1
                            grdData.Rows.Band.Columns(lobjTop1DataSources.ResearchSourceCol).CellAppearance.BackColor = grdData.DisplayLayout.Appearances("VisiblePosition").BackColor
                            grdData.Rows.Band.Columns(lobjTop1DataSources.ResearchSourceCol).CellActivation = Activation.AllowEdit
                        End If
                    End If
                End If
                lintRowCounter -= 1
            End While

            'Set the index/location of the corresponding previous project's data source
            SetPreviousProjectDataSourcesVisibility(lobjTop1DataSources, True, lintSourceColCount)
        Else
            'Otherwise, if its unlock functionality
            lintRowCounter = 0
            lobjTop1DataSources = Nothing
            'For each unlocked column, set the backcolor to normal, mark it NoEdit
            For Each lobjCurrentDataSources As CurrentDataSources In mstCurrentDataSources
                If lobjCurrentDataSources.AccessStatus = SourceAccessbility.Unlocked.ToString Then
                    If lobjTop1DataSources Is Nothing Then
                        lobjTop1DataSources = lobjCurrentDataSources
                    End If
                    grdData.Rows.Band.Columns(lobjCurrentDataSources.SourceName).CellActivation = Activation.NoEdit
                    grdData.Rows.Band.Columns(lobjCurrentDataSources.SourceName).CellAppearance.BackColor = grdData.DisplayLayout.Appearances("CancelCutRowBackColor").BackColor
                    lstrSourceDateCol = lobjCurrentDataSources.SourceName + mstrSourceDateColSuffix
                    If mstAllDataSourceDateCols.Contains(lstrSourceDateCol) Then
                        grdData.Rows.Band.Columns(lstrSourceDateCol).CellAppearance.BackColor = grdData.DisplayLayout.Appearances("CancelCutRowBackColor").BackColor
                        grdData.Rows.Band.Columns(lstrSourceDateCol).CellActivation = Activation.NoEdit
                    End If
                    If mstResearchSourceCols.Contains(lobjTop1DataSources.ResearchSourceCol) Then
                        grdData.Rows.Band.Columns(lobjTop1DataSources.ResearchSourceCol).CellAppearance.BackColor = grdData.DisplayLayout.Appearances("CancelCutRowBackColor").BackColor
                        grdData.Rows.Band.Columns(lobjTop1DataSources.ResearchSourceCol).CellActivation = Activation.NoEdit
                    End If
                End If
            Next

            'For each unlocked column, Hide the corresponding previous data sources
            SetPreviousProjectDataSourcesVisibility(lobjTop1DataSources, False, 0)

            'Set the given data source column(s) to normal color for Investor rows
            For Each lobjCurrentDataSources As CurrentDataSources In mstCurrentDataSources
                If lobjCurrentDataSources.AccessStatus = SourceAccessbility.Unlocked.ToString Then
                    lstrSourceDateCol = lobjCurrentDataSources.SourceName + mstrSourceDateColSuffix
                    lstrResearchSource = lobjCurrentDataSources.SourceName + mstrSourceColSuffix
                    For Each lUltraRow As UltraGridRow In grdData.Rows
                        If lUltraRow.GetCellValue("LinkID") <> 0 Then Continue For
                        lUltraRow.Cells(lobjCurrentDataSources.SourceName).Appearance.BackColor = grdData.DisplayLayout.Appearances("GridInvBackColor").BackColor 'mclrGridInvBackColor
                        If mstAllDataSourceDateCols.Contains(lstrSourceDateCol) Then
                            lUltraRow.Cells(lstrSourceDateCol).Appearance.BackColor = grdData.DisplayLayout.Appearances("GridInvBackColor").BackColor  'mclr
                        End If
                        If mstResearchSourceCols.Contains(lstrResearchSource) Then
                            lUltraRow.Cells(lstrResearchSource).Appearance.BackColor = grdData.DisplayLayout.Appearances("GridInvBackColor").BackColor  'mclr
                        End If
                    Next
                End If
            Next

            'Set the unlocked columns to Neutral state
            For Each lobjCurrentDataSources As CurrentDataSources In mstCurrentDataSources
                If lobjCurrentDataSources.AccessStatus = SourceAccessbility.Unlocked.ToString Then
                    lobjCurrentDataSources.AccessStatus = SourceAccessbility.Neutral.ToString
                End If
            Next
        End If
    End Sub

    ''' <summary>
    ''' To set the visibility of previous project's data sources
    ''' </summary>
    ''' <param name="lobjTop1DataSources"></param>
    ''' <param name="pblnIsLocked"></param>
    ''' <param name="lintSourceColCount"></param>
    ''' <remarks></remarks>
    Private Sub SetPreviousProjectDataSourcesVisibility(ByVal lobjTop1DataSources As CurrentDataSources, ByVal pblnIsLocked As Boolean, ByVal lintSourceColCount As Integer)
        Dim lstListing As New List(Of String)
        Dim lstrSourceFirstName As String
        Try
            If lobjTop1DataSources.SourceTypeCode = SourceTypeCode.UPD.ToString Then
                lstrSourceFirstName = lobjTop1DataSources.SourceName.Substring(0, lobjTop1DataSources.SourceName.Length - lobjTop1DataSources.ListingName.Length)
                For Each lobjCurrentDataSources As CurrentDataSources In mstCurrentDataSources
                    If lstListing.Contains(lobjCurrentDataSources.ListingName) = False Then
                        lstListing.Add(lobjCurrentDataSources.ListingName)
                        For Each lobjPreviousDataSources As PreviousDataSources In mstPreviousDataSources
                            If lobjPreviousDataSources.SourceName = mstrPreviousProjectName + " " + lstrSourceFirstName + lobjCurrentDataSources.ListingName AndAlso _
                                grdData.Rows.Band.Columns.Exists(lobjPreviousDataSources.SourceName) Then
                                grdData.Rows.Band.Columns(lobjPreviousDataSources.SourceName).Hidden = Not pblnIsLocked
                                If pblnIsLocked Then
                                    grdData.Rows.Band.Columns(lobjPreviousDataSources.SourceName).Header.VisiblePosition = grdData.Rows.Band.Columns("Parent").Header.VisiblePosition + lintSourceColCount + 1
                                End If
                                'If grdData.Rows.Band.Columns.Exists(lobjPreviousDataSources.SourceName + mstrSourceDateColSuffix) Then
                                '    grdData.Rows.Band.Columns(lobjPreviousDataSources.SourceName + mstrSourceDateColSuffix).Hidden = Not pblnIsLocked
                                '    If pblnIsLocked Then
                                '        grdData.Rows.Band.Columns(lobjPreviousDataSources.SourceName + mstrSourceDateColSuffix).Header.VisiblePosition = grdData.Rows.Band.Columns(lobjPreviousDataSources.SourceName).Header.VisiblePosition + 1
                                '    End If
                                'End If
                            End If
                        Next
                    End If
                Next
            Else
                For Each lobjPreviousDataSources As PreviousDataSources In mstPreviousDataSources
                    If lobjTop1DataSources.ListingName = lobjPreviousDataSources.ListingName AndAlso lobjTop1DataSources.SourceTypeCode = lobjPreviousDataSources.SourceTypeCode _
                    AndAlso lobjTop1DataSources.ESourceName = lobjPreviousDataSources.ESourceName AndAlso grdData.Rows.Band.Columns.Exists(lobjPreviousDataSources.SourceName) Then
                        grdData.Rows.Band.Columns(lobjPreviousDataSources.SourceName).Hidden = Not pblnIsLocked
                        If pblnIsLocked Then
                            grdData.Rows.Band.Columns(lobjPreviousDataSources.SourceName).Header.VisiblePosition = grdData.Rows.Band.Columns("Parent").Header.VisiblePosition + lintSourceColCount + 1
                        End If
                        'If grdData.Rows.Band.Columns.Exists(lobjPreviousDataSources.SourceName + mstrSourceDateColSuffix) Then
                        '    grdData.Rows.Band.Columns(lobjPreviousDataSources.SourceName + mstrSourceDateColSuffix).Hidden = Not pblnIsLocked
                        '    If pblnIsLocked Then
                        '        grdData.Rows.Band.Columns(lobjPreviousDataSources.SourceName + mstrSourceDateColSuffix).Header.VisiblePosition = grdData.Rows.Band.Columns(lobjPreviousDataSources.SourceName).Header.VisiblePosition + 1
                        '    End If
                        'End If
                    End If
                Next
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            lstListing = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' To remove the uncessary associted columns of data sources
    ''' </summary>
    ''' <param name="ldtUpdatedData"></param>
    ''' <param name="lstActiveDataSources"></param>
    ''' <remarks></remarks>
    Private Sub RemoveUnnecessaryAssociatedFields(ByRef ldtUpdatedData As DataTable, ByVal lstActiveDataSources As List(Of CurrentDataSources))
        'For Each lCol As DataColumn In ldtCurrentData-
        For Each lobjColName As CurrentDataSources In lstActiveDataSources
            If lobjColName.SourceTypeCode = SourceTypeCode.PBC.ToString Then
                If ldtUpdatedData.Columns.Contains(lobjColName.SourceName + mstrFilingDateColSuffix) = False Then
                    ldtUpdatedData.Columns.Add(lobjColName.SourceName + mstrSourceColSuffix, GetType(String))
                    ldtUpdatedData.Columns.Add(lobjColName.SourceName + mstrFilingDateColSuffix, GetType(String))
                End If
            Else
                If ldtUpdatedData.Columns.Contains(lobjColName.SourceName + mstrFilingDateColSuffix) Then
                    ldtUpdatedData.Columns.Remove(lobjColName.SourceName + mstrSourceColSuffix)
                    ldtUpdatedData.Columns.Remove(lobjColName.SourceName + mstrFilingDateColSuffix)
                End If
            End If
            If lobjColName.SourceTypeCode = SourceTypeCode.RSH.ToString Then
                If ldtUpdatedData.Columns.Contains(lobjColName.SourceName + mstrClientSpecificSourceColSuffix) = False Then
                    ldtUpdatedData.Columns.Add(lobjColName.SourceName + mstrClientSpecificSourceColSuffix, GetType(String))
                    ldtUpdatedData.Columns.Add(lobjColName.SourceName + mstrGenericSourceColSuffix, GetType(String))
                    ldtUpdatedData.Columns.Add(lobjColName.SourceName + mstrSourceColSuffix, GetType(String))
                End If
            Else
                If ldtUpdatedData.Columns.Contains(lobjColName.SourceName + mstrClientSpecificSourceColSuffix) Then
                    ldtUpdatedData.Columns.Remove(lobjColName.SourceName + mstrClientSpecificSourceColSuffix)
                    ldtUpdatedData.Columns.Remove(lobjColName.SourceName + mstrGenericSourceColSuffix)
                    ldtUpdatedData.Columns.Remove(lobjColName.SourceName + " RSource")
                End If
            End If
            'If marrEditableSourceTypes.Contains(lobjColName.SourceTypeCode) = False Then
            '    If ldtUpdatedData.Columns.Contains(lobjColName.SourceName + mstrFormulaColSuffix) Then
            '        ldtUpdatedData.Columns.Remove(lobjColName.SourceName + mstrFormulaColSuffix)
            '        ldtUpdatedData.Columns.Remove(mstrSOFColPrefix + lobjColName.SourceName)
            '    End If
            'End If
            If marrDateSuppertedSourceTypes.Contains(lobjColName.ESourceCode) Then
                If ldtUpdatedData.Columns.Contains(lobjColName.SourceName + mstrSourceDateColSuffix) = False Then
                    ldtUpdatedData.Columns.Add(lobjColName.SourceName + mstrSourceDateColSuffix, GetType(Date))
                End If
            Else
                If ldtUpdatedData.Columns.Contains(lobjColName.SourceName + mstrSourceDateColSuffix) Then
                    ldtUpdatedData.Columns.Remove(lobjColName.SourceName + mstrSourceDateColSuffix)
                End If
            End If
        Next

        For Each lobjColName As CurrentDataSources In lstActiveDataSources
            If lobjColName.SourceTypeCode = SourceTypeCode.RSH.ToString Then
                If ldtUpdatedData.Columns.Contains(lobjColName.SourceName + " RSource") Then
                    ldtUpdatedData.Columns(lobjColName.SourceName + " RSource").ColumnName = lobjColName.SourceName + mstrSourceColSuffix
                End If
            End If
        Next
    End Sub

    ''' <summary>
    ''' Get the updated data for Sum Of Funds and Formula
    ''' </summary>
    ''' <param name="lstrSelectedEntities"></param>
    ''' <remarks></remarks>
    Private Sub GetUpdatedDataForSOFFormula(ByVal lstrSelectedEntities As String, ByVal lstrSelectedDataEntities As String, ByVal lstActiveDataSources As List(Of CurrentDataSources))
        Dim lstNonPivotCols As New List(Of String)
        Dim lstPivotCols As New List(Of String)
        Dim ldtUpdatedData As DataTable = Nothing
        Try
            lstNonPivotCols.Add("InvestorID")
            lstNonPivotCols.Add("FundID")
            lstPivotCols.Add(mstrFormulaColSuffix.Trim)
            lstPivotCols.Add(mstrSOFColPrefix)
            'Get the updated data from the database
            mdtDEAssociatedData = mclsDataHubManager.GetUpdatedDataForSOFFormula(mintProjectID, lstrSelectedEntities, lstNonPivotCols, lstPivotCols, mstrPreviousProjectName)
            SetPrimaryKey(mdtDEAssociatedData)
            AddMissingSOFFormulaCols(lstActiveDataSources)
            mdtDEAssociatedData.AcceptChanges()
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            lstNonPivotCols = Nothing
            lstPivotCols = Nothing
        End Try
    End Sub

    Private Sub AddMissingSOFFormulaCols(ByVal lstActiveDataSources As List(Of CurrentDataSources))
        For Each lobjActiveDataSource As CurrentDataSources In lstActiveDataSources
            If mdtDEAssociatedData.Columns.Contains(mstrSOFColPrefix + lobjActiveDataSource.SourceName) = False Then
                mdtDEAssociatedData.Columns.Add(mstrSOFColPrefix + lobjActiveDataSource.SourceName, GetType(Boolean))
                mdtDEAssociatedData.Columns.Add(lobjActiveDataSource.SourceName + mstrFormulaColSuffix, GetType(String))
            End If
        Next
    End Sub

    ''' <summary>
    ''' To add the Investor and Fund columnns in the passed datatable
    ''' </summary>
    ''' <param name="ldtData"></param>
    ''' <remarks></remarks>
    Private Sub AddMissingInvestorFundCols(ByVal ldtData As DataTable)
        ldtData.Columns.Add("InvestorID", GetType(Integer))
        ldtData.Columns.Add("FundID", GetType(Integer))
    End Sub

    ''' <summary>
    ''' Get the column level updated data for the locking column
    ''' </summary>
    ''' <param name="lstrSelectedEntities"></param>
    ''' <remarks></remarks>
    Private Sub GetLockedEntityUpdatedData(ByVal lstrSelectedEntities As String, ByVal lstrSelectedDataEntities As String, _
                                           ByVal lstActiveDataSources As List(Of CurrentDataSources), ByVal pblnCanRetrievePreviousDataSources As Boolean, _
                                           ByVal pblnCanIgnoreAddColumns As Boolean)
        Dim ldtCurrentData As DataTable = Nothing
        Dim ldtUpdatedData As DataTable = Nothing
        Dim lstNonPivotCols As New List(Of String)
        Dim lstPivotCols As New List(Of String)
        Dim lintColCounter As Integer
        Dim lstrTraversingColName As String
        Dim sqlBulkCopy As System.Data.SqlClient.SqlBulkCopy = Nothing
        Dim ldtInvFundData As DataTable = Nothing
        Dim lintPreviousProjectID As Integer = 0
        'Dim lintUpdatedDataColCounter As Integer
        'Dim lstrColName As String
        Try
            If pblnCanRetrievePreviousDataSources Then
                lintPreviousProjectID = mintPreviousProjectID
            End If
            ldtCurrentData = grdData.DataSource
            '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            ' ''''''''''''''''''''Starts: Code for Unpivot'''''''''''''''''''''''''''''''''''''
            'Dim ldtSourcePivoted As New DataTable
            'ldtSourcePivoted.Columns.Add("InvestorID", GetType(Integer))
            'ldtSourcePivoted.Columns.Add("FundID", GetType(Integer))
            'For Each lobjDataSource As CurrentDataSources In lstActiveDataSources
            '    ldtSourcePivoted.Columns.Add(lobjDataSource.SourceName, GetType(Int64))
            '    ldtSourcePivoted.Columns.Add(lobjDataSource.SourceName + mstrSourceDateColSuffix, GetType(Date))
            '    ldtSourcePivoted.Columns.Add(mstrSOFColPrefix + lobjDataSource.SourceName, GetType(Boolean))
            '    ldtSourcePivoted.Columns.Add(lobjDataSource.SourceName + mstrFormulaColSuffix, GetType(String))
            '    ldtSourcePivoted.Columns.Add(lobjDataSource.SourceName + mstrClientSpecificSourceColSuffix, GetType(String))
            '    ldtSourcePivoted.Columns.Add(lobjDataSource.SourceName + mstrGenericSourceColSuffix, GetType(String))
            '    lstPivotCols.Add(lobjDataSource.SourceName)
            'Next

            'ldtSourcePivoted.Merge(ldtCurrentData, False, MissingSchemaAction.Ignore)
            ''mclsDataHubManager.SukhUnPivot(ldtSourcePivoted, lstPivotCols)
            'Dim ldtUnpivotedData As DataTable
            'ldtUnpivotedData = mclsDataHubManager.SukhUnPivot(ldtSourcePivoted, lstActiveDataSources, mintProjectID)
            'Dim sqlBulkCopy As System.Data.SqlClient.SqlBulkCopy = Nothing

            ''Clear the staging table for the given ProjectID and UserID
            'CommonManager.ClearDHSortBulkStagingTable("STG_LockedEntityData", CommonCLL.UserID, mintProjectID)
            'sqlBulkCopy = New System.Data.SqlClient.SqlBulkCopy(mstrConnectionstring)
            ''Define column mappings to specify the columnn/data to be saved in staging table
            'sqlBulkCopy.DestinationTableName = "STG_LockedEntityData"
            'sqlBulkCopy.ColumnMappings.Add("InvestorID", "InvestorID")
            'sqlBulkCopy.ColumnMappings.Add("FundID", "FundID")
            'sqlBulkCopy.ColumnMappings.Add("EntityID", "EntityID")
            'sqlBulkCopy.ColumnMappings.Add("Position", "Position")
            'sqlBulkCopy.ColumnMappings.Add("SourceDate", "SourceDate")
            'sqlBulkCopy.ColumnMappings.Add("IsSumOfFunds", "IsSumOfFunds")
            'sqlBulkCopy.ColumnMappings.Add("Formula", "Formula")
            'sqlBulkCopy.ColumnMappings.Add("ClientSpecificSource", "ClientSpecificSource")
            'sqlBulkCopy.ColumnMappings.Add("GenericSource", "GenericSource")
            'sqlBulkCopy.ColumnMappings.Add("UserID", "UserID")
            'sqlBulkCopy.ColumnMappings.Add("ProjectID", "ProjectID")

            ''Write data in the staging table
            'sqlBulkCopy.WriteToServer(ldtUnpivotedData)
            'sqlBulkCopy.Close()
            'sqlBulkCopy = Nothing

            ' ''''''''''''''''''''Ends: Code for Unpivot'''''''''''''''''''''''''''''''''''''''
            '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            lstNonPivotCols.Add("InvestorID")
            lstNonPivotCols.Add("FundID")
            lstPivotCols.Add("Position")
            lstPivotCols.Add(mstrFormulaColSuffix.Trim)
            lstPivotCols.Add(mstrSOFColPrefix)
            lstPivotCols.Add(mstrSourceDateColSuffix.Trim)
            lstPivotCols.Add(mstrFilingDateColSuffix.Trim)
            lstPivotCols.Add(mstrSourceColSuffix.Trim)
            lstPivotCols.Add(mstrClientSpecificSourceColSuffix.Trim)
            lstPivotCols.Add(mstrGenericSourceColSuffix.Trim)
            lstPivotCols.Add("RSource")

            ' ''''''''''''''''''Starts: To store the InvestorID ans FundID in staging table so that they can be matched AND are NOT selected when new rows are being selected''''''
            'CommonManager.ClearDHSortBulkStagingTable("STG_LockedEntityData", CommonCLL.UserID, mintProjectID)
            'sqlBulkCopy = New System.Data.SqlClient.SqlBulkCopy(mstrConnectionstring)
            ''Define column mappings to specify the columnn/data to be saved in staging table
            'sqlBulkCopy.DestinationTableName = "STG_LockedEntityData"
            'sqlBulkCopy.ColumnMappings.Add("InvestorID", "InvestorID")
            'sqlBulkCopy.ColumnMappings.Add("LinkID", "LinkID")
            'sqlBulkCopy.ColumnMappings.Add("ProjectID", "ProjectID")
            'sqlBulkCopy.ColumnMappings.Add("UserID", "UserID")
            'sqlBulkCopy.WriteToServer(ldtCurrentData)
            'sqlBulkCopy.Close()
            'sqlBulkCopy = Nothing
            ' ''''''''''''''''''Ends: To store the InvestorID ans FundID in staging table so that they can be matched AND are NOT selected when new rows are being selected''''''

            mclsDataHubManager.UpdateAndGetProjectDatabase(ldtCurrentData, mintProjectID)
            mblnAnyChangesInLastProject = True
            'Get the updated data from the database
            ldtUpdatedData = mclsDataHubManager.GetLockedUpdatedData(mintProjectID, lstrSelectedEntities, lstNonPivotCols, lstPivotCols, mstrPreviousProjectName, _
                                                                     lstActiveDataSources, lintPreviousProjectID, ldtInvFundData)
            'SetPrimaryKey(ldtInvFundData)
            SetPrimaryKey(ldtUpdatedData)
            'Make changes in the grid's columns accordingly, Disable AfterCellUpdate event when the data is being updated in the grid

            grdData.EventManager.SetEnabled(Infragistics.Win.UltraWinGrid.GridEventIds.AfterCellUpdate, False)
            grdData.BeginUpdate()
            grdData.SuspendRowSynchronization()

            RemoveUnnecessaryAssociatedFields(ldtUpdatedData, lstActiveDataSources)

            mdtDEAssociatedData = New DataTable
            mdtDEAssociatedData = ldtUpdatedData.Copy
            Dim columnNames = mdtDEAssociatedData.Columns.Cast(Of DataColumn)() _
                              .Select(Function(column) column.ColumnName).ToArray()
            lintColCounter = columnNames.Length - 1
            While lintColCounter >= 0
                lstrTraversingColName = columnNames(lintColCounter)
                'lstrTraversingColName = mdtDEAssociatedData.Columns(lintColCounter).ColumnName
                If lstrTraversingColName.Equals("InvestorID") OrElse lstrTraversingColName.Equals("FundID") Then
                    lintColCounter -= 1
                    Continue While
                End If
                If lstrTraversingColName.StartsWith(mstrSOFColPrefix) = False AndAlso lstrTraversingColName.EndsWith(mstrFormulaColSuffix) = False Then
                    mdtDEAssociatedData.Columns.Remove(lstrTraversingColName)
                Else
                    ldtUpdatedData.Columns.Remove(lstrTraversingColName)
                End If
                lintColCounter -= 1
            End While
            AddMissingSOFFormulaCols(lstActiveDataSources)
            mdtDEAssociatedData.AcceptChanges()
            'ldtUpdatedData.AcceptChanges()
            ldtCurrentData.AcceptChanges()
            'ldtInvFundData.AcceptChanges()
            If pblnCanIgnoreAddColumns Then
                ''''''Starts: Sukhminder Singh - 26th Sep 2012 - Follow below, If all values are to be set to blank and then to update using merge
                For Each lobjDataSource As CurrentDataSources In lstActiveDataSources
                    For Each lrow As DataRow In ldtCurrentData.Rows
                        lrow.Item(lobjDataSource.SourceName) = ""
                        If lobjDataSource.SourceTypeCode = SourceTypeCode.PBC.ToString Then
                            lrow.Item(lobjDataSource.PublicSourceCol) = ""
                            lrow.Item(lobjDataSource.PublicFilingDateCol) = ""
                        End If
                    Next
                Next
                'ldtCurrentData.Merge(ldtInvFundData, False, MissingSchemaAction.Ignore)
                ldtCurrentData.Merge(ldtUpdatedData, False, MissingSchemaAction.Ignore)
                ''''''Ends: Sukhminder Singh - 26th Sep 2012 - Follow below, If all values are to be set to blank and then to update using merge

                ''''''Starts: Sukhminder Singh - 26th Sep 2012 - Follow below, If a deletion and addition of column is required
                'For Each lobjDataSource As CurrentDataSources In lstActiveDataSources
                '    ldtCurrentData.Columns.Remove(lobjDataSource.SourceName)
                '    If lobjDataSource.SourceTypeCode = SourceTypeCode.PBC.ToString Then
                '        ldtCurrentData.Columns.Remove(lobjDataSource.PublicSourceCol)
                '        ldtCurrentData.Columns.Remove(lobjDataSource.PublicFilingDateCol)
                '    End If
                'Next
                'ldtCurrentData.AcceptChanges()
                'ldtInvFundData.AcceptChanges()
                'ldtUpdatedData.AcceptChanges()
                'ldtCurrentData.Merge(ldtInvFundData, False, MissingSchemaAction.Add)
                'ldtCurrentData.Merge(ldtUpdatedData, False, MissingSchemaAction.Add)
                ''''''Ends: Sukhminder Singh - 26th Sep 2012 - Follow below, If a deletion and addition of column is required
            Else
                'ldtCurrentData.Merge(ldtInvFundData, False, MissingSchemaAction.Add)
                'ldtCurrentData.AcceptChanges()
                'ldtUpdatedData.AcceptChanges()
                ldtCurrentData.Merge(ldtUpdatedData, False, MissingSchemaAction.Add)
            End If

            If mstrPreviousProjectName.Equals("") = False Then
                For Each lCol As DataColumn In ldtUpdatedData.Columns
                    If lCol.ColumnName.StartsWith(mstrPreviousProjectName) Then
                        grdData.DisplayLayout.Bands(0).Columns(lCol.ColumnName).Editor.DataFilter = New ThousandFormatter()
                    End If
                Next
            End If
            ldtCurrentData.AcceptChanges()
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            ldtInvFundData = Nothing
            grdData.Update()
            grdData.ResumeRowSynchronization()
            grdData.EndUpdate()
            grdData.EventManager.SetEnabled(Infragistics.Win.UltraWinGrid.GridEventIds.AfterCellUpdate, True)
            ldtUpdatedData = Nothing
            ldtCurrentData = Nothing
            lstNonPivotCols = Nothing
            lstPivotCols = Nothing
        End Try
    End Sub

#End Region

#Region "Cell And Value Related"

    ''' <summary>
    ''' To set a particular cell in edit mode
    ''' </summary>
    ''' <param name="lCell"></param>
    ''' <param name="pblnCanChangeToEditMode"></param>
    ''' <remarks></remarks>
    Private Sub SetCellInEditMode(ByRef lCell As UltraGridCell, ByVal pblnCanChangeToEditMode As Boolean)
        'Check if the cell could be change to Edit mode, if yes do so
        Dim lstrFormula As String
        If pblnCanChangeToEditMode Then
            grdData.PerformAction(UltraGridAction.EnterEditMode, False, False)
        End If
        'If the cell has a formula, then show the formula instead of value in Edit mode
        lstrFormula = GetFormula(grdData.ActiveRow.GetCellValue("InvestorID"), grdData.ActiveRow.GetCellValue("FundID"), grdData.ActiveRow.GetCellValue("LinkID"), lCell.Column.Header.Caption, True)
        If lstrFormula <> String.Empty Then
            lCell.Value = lstrFormula
        End If
    End Sub

    ''' <summary>
    ''' To set the Investor and Managed Fund positions for the passed Investor and it's rows
    ''' </summary>
    ''' <param name="penmInvestorPositionSources">Type of Source, Cell change or RevertToSum</param>
    ''' <param name="pblnIsFromDataSource">Check if its a datasource cell</param>
    ''' <param name="pultracellCurrent">The cell in which change is being made</param>
    ''' <remarks></remarks>
    Private Sub CalculateInvAndManagedFundPositions(ByVal penmInvestorPositionSources As InvestorPositionSources, ByVal pblnIsFromDataSource As Boolean, ByVal pultracellCurrent As UltraGridCell)
        'Find the column index on which operations have to be performed
        Dim lintActiveColIndex As Integer = pultracellCurrent.Column.Index
        Dim lstrActiveColName As String = pultracellCurrent.Column.Header.Caption
        'Find the row index on which operations have to be performed
        Dim lintActiveRowIndex As Integer = pultracellCurrent.Row.Index
        Dim lintSum As Integer = 0
        Dim lintRowCounter As Integer = lintActiveRowIndex
        Dim lintInvestorRowIndex As Integer
        Dim lintManagedFundIndex As Integer = -1
        Dim lintManagedFundPosition As Int64 = 0
        Dim lintInvestorPosition As Int64 = 0
        Dim lblnIsSumOfFunds As Boolean = True
        Dim lobjCurrentDataSource As CurrentDataSources = Nothing
        Dim lugrWorkingRow As UltraGridRow = grdData.Rows(lintRowCounter)
        Dim lblnCanToplineBe0 As Boolean
        Try
            'Check if has come from CellChange
            If penmInvestorPositionSources = InvestorPositionSources.OnCellChange Then
                'Check if its an Investor
                If lugrWorkingRow.GetCellValue("LinkID") = 0 Then
                    'If the value and positions don't match, it means it's not a sum of funds, hence set it to false
                    If pultracellCurrent.Text <> pultracellCurrent.Value.ToString Then
                        SetAssociatedIsSumOfFunds(lugrWorkingRow.GetCellValue("InvestorID"), lugrWorkingRow.GetCellValue("FundID"), lstrActiveColName, False)
                        'lugrWorkingRow.Cells(mstrSOFColPrefix + lstrActiveColName).Value = False
                    End If
                    'If it's sum of funds, then exit from the procedure, because Investor or Managed Fund's position are required to set from here only if the Investor is not a Sum Of Funds
                    'lblnIsSumOfFunds = CommonCLL.IsNullToTrueForBool(lugrWorkingRow.GetCellValue(mstrSOFColPrefix + lstrActiveColName))
                    lblnIsSumOfFunds = CheckSumOfFunds(lugrWorkingRow.GetCellValue("InvestorID"), lstrActiveColName, True, True)
                    If lblnIsSumOfFunds Then
                        Exit Sub
                    End If
                End If
            End If

            'The following code calculates the value of all associated fund's positions and managed fund so that appropriate values can be given to the Investor Row and Managed Fund row
            'Logic is that if the Investor is Sum of Funds, then Managed Fund is considered as a Normal Fund, but if its not, then the Managed Fund will be the differene 
            'bet-ween Investor Position and sum of Non-Managed Funds of that investor

            'This while loop starts from the selected row and goes upward till it's investor row
            While lintRowCounter >= 0
                'If the loop reaches to the Investor Row, then save it's text value in a variable
                If lugrWorkingRow.GetCellValue("LinkID") = 0 Then
                    If lugrWorkingRow.Cells(lstrActiveColName).Text.Equals("") = False AndAlso lugrWorkingRow.Cells(lstrActiveColName).Text.Equals(mstrNDValue) = False Then
                        lintInvestorPosition = lugrWorkingRow.Cells(lstrActiveColName).Text
                    End If
                    lintInvestorRowIndex = lintRowCounter
                    Exit While
                End If

                'If it's a managed fund, then store it's positions in a variable
                If lugrWorkingRow.GetCellValue("IsManaged") = True Then
                    lintManagedFundIndex = lintRowCounter
                    If lugrWorkingRow.GetCellValue(lstrActiveColName).ToString.Equals("") = False AndAlso lugrWorkingRow.GetCellValue(lstrActiveColName).ToString.Equals(mstrNDValue) = False Then
                        lintManagedFundPosition = lugrWorkingRow.GetCellValue(lstrActiveColName)
                    End If
                End If
                'If the value is blank OR if it's a Cut row, then don't consider it's value in calculation of the Investor position
                If lugrWorkingRow.Cells(lstrActiveColName).Text.Equals("") OrElse lugrWorkingRow.Cells(lstrActiveColName).Text.Equals(mstrNDValue) OrElse lugrWorkingRow.GetCellValue("IsCutRow") Then
                    lintRowCounter -= 1
                    If lintRowCounter < 0 Then Exit While
                    lugrWorkingRow = grdData.Rows(lintRowCounter)
                    Continue While
                End If
                'Adding the fund's positions in a variable to formulate Investor's positions
                lintSum += lugrWorkingRow.Cells(lstrActiveColName).Text
                lintRowCounter -= 1
                If lintRowCounter < 0 Then Exit While
                lugrWorkingRow = grdData.Rows(lintRowCounter)
            End While

            'If the Source of the position update is RevertToSumofFunds then set the SOF value of the row to true
            If penmInvestorPositionSources = InvestorPositionSources.RevertToSumOfFunds Then
                SetAssociatedIsSumOfFunds(grdData.Rows(lintInvestorRowIndex).GetCellValue("InvestorID"), grdData.Rows(lintInvestorRowIndex).GetCellValue("FundID"), lstrActiveColName, True)
                'ldrAssociatedData(mstrSOFColPrefix + lstrActiveColName) = True
                'grdData.Rows(lintInvestorRowIndex).Cells(mstrSOFColPrefix + lstrActiveColName).Value = True
            End If

            'This while loop starts from the row next to the currently selected row and goes downward till it's last associated fund row
            lintRowCounter = lintActiveRowIndex + 1
            If lintRowCounter < grdData.Rows.Count Then
                lugrWorkingRow = grdData.Rows(lintRowCounter)
            End If
            While lintRowCounter < grdData.Rows.Count And lugrWorkingRow.GetCellValue("LinkID") <> 0
                'If it's a managed fund, then store it's positions in a variable
                If lugrWorkingRow.GetCellValue("IsManaged") = True Then
                    lintManagedFundIndex = lintRowCounter
                    If lugrWorkingRow.GetCellValue(lstrActiveColName).ToString.Equals("") = False AndAlso lugrWorkingRow.GetCellValue(lstrActiveColName).ToString.Equals(mstrNDValue) = False Then
                        lintManagedFundPosition = lugrWorkingRow.GetCellValue(lstrActiveColName)
                    End If
                End If
                'If the value is blank OR if it's a Cut row, then don't consider it's value in calculation of the Investor position
                If lugrWorkingRow.Cells(lstrActiveColName).Text.Equals("") OrElse lugrWorkingRow.Cells(lstrActiveColName).Text.Equals(mstrNDValue) OrElse lugrWorkingRow.GetCellValue("IsCutRow") Then
                    lintRowCounter += 1
                    If lintRowCounter = grdData.Rows.Count Then Exit While
                    lugrWorkingRow = grdData.Rows(lintRowCounter)
                    Continue While
                End If
                lintSum += lugrWorkingRow.Cells(lstrActiveColName).Text
                lintRowCounter += 1
                If lintRowCounter = grdData.Rows.Count Then Exit While
                lugrWorkingRow = grdData.Rows(lintRowCounter)
            End While

            'Check if the currently selected column supports SOF column
            'lblnIsSumOfFunds = ldrFLAssociatedData("~")
            lblnIsSumOfFunds = CheckSumOfFunds(grdData.Rows(lintInvestorRowIndex).GetCellValue("InvestorID"), lstrActiveColName, True, True)

            'If SOF is true
            If lblnIsSumOfFunds Then
                'If it's SOF and it's Formula is not blank, then set it to blank
                If GetFormula(grdData.Rows(lintInvestorRowIndex).GetCellValue("InvestorID"), grdData.Rows(lintInvestorRowIndex).GetCellValue("FundID"), grdData.Rows(lintInvestorRowIndex).GetCellValue("LinkID"), lstrActiveColName, True).Equals("") = False Then
                    SetAssociatedFormula(grdData.Rows(lintInvestorRowIndex).GetCellValue("InvestorID"), grdData.Rows(lintInvestorRowIndex).GetCellValue("FundID"), lstrActiveColName, "")
                    'grdData.Rows(lintInvestorRowIndex).Cells(lstrActiveColName + mstrFormulaColSuffix).Value = ""
                End If

                'Check if Sum of the Funds becomes zero
                If lintSum = 0 Then
                    lblnCanToplineBe0 = False
                    ''''Starts: Commented because now we need to show blank instead of 0 in case the SOF is 0, for all data sources
                    ''If it's from DataSource, then check if its such a source which supports zero at the Topline
                    'If pblnIsFromDataSource Then
                    '    lobjCurrentDataSource = mstCurrentDataSources.Find(Function(p) p.SourceName = grdData.Rows(lintInvestorRowIndex).Cells(lintActiveColIndex).Column.Header.Caption)
                    '    If lobjCurrentDataSource IsNot Nothing Then
                    '        If marrToplineNot0.Contains(lobjCurrentDataSource.SourceTypeCode) Then
                    '            lblnCanToplineBe0 = False
                    '        End If
                    '    End If
                    'End If
                    ''''Ends: Commented because now we need to show blank instead of 0 in case the SOF is 0, for all data sources

                    'If zero position cannot be given to selected source, then set Blank
                    If lblnCanToplineBe0 = False Then
                        grdData.Rows(lintInvestorRowIndex).Cells(lintActiveColIndex).SetValue("", True)
                    Else
                        'Otherwise give it zero position
                        grdData.Rows(lintInvestorRowIndex).Cells(lintActiveColIndex).SetValue(lintSum, True)
                    End If
                Else
                    'If Sum of Funds is non-zero, simply set Investor position
                    grdData.Rows(lintInvestorRowIndex).Cells(lintActiveColIndex).SetValue(lintSum, True)
                End If
            Else
                'If SOF is false, deduct managed fund's positions from Investor's position and assign it
                If lintManagedFundIndex <> -1 Then
                    lintSum -= lintManagedFundPosition
                    grdData.Rows(lintManagedFundIndex).Cells(lintActiveColIndex).SetValue(lintInvestorPosition - lintSum, True)
                    'grdData.Rows(lintManagedFundIndex).Cells(lintActiveColIndex).Value = lintInvestorPosition - lintSum
                End If
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            lobjCurrentDataSource = Nothing
            lugrWorkingRow = Nothing
        End Try
    End Sub

    Private Sub AddAssociatedRow(ByRef ldtTargetData As DataTable, ByVal pintInvestorID As Integer, ByVal pintFundID As Integer, ByVal lstrActiveColName As String, ByVal lblnIsSumOfFunds As Boolean, ByVal lstrFormula As String)
        Dim ldrAssociatedData As DataRow = Nothing
        ldrAssociatedData = ldtTargetData.NewRow
        ldrAssociatedData.Item("InvestorID") = pintInvestorID
        ldrAssociatedData.Item("FundID") = pintFundID
        If ldtTargetData.Columns.Contains(mstrSOFColPrefix + lstrActiveColName) = False Then
            ldtTargetData.Columns.Add(mstrSOFColPrefix + lstrActiveColName, GetType(Boolean))
        End If
        If ldtTargetData.Columns.Contains(lstrActiveColName + mstrFormulaColSuffix) = False Then
            ldtTargetData.Columns.Add(lstrActiveColName + mstrFormulaColSuffix, GetType(String))
        End If
        ldrAssociatedData.Item(mstrSOFColPrefix + lstrActiveColName) = lblnIsSumOfFunds
        ldrAssociatedData.Item(lstrActiveColName + mstrFormulaColSuffix) = lstrFormula
        'For Each lCol As DataColumn In ldtTargetData.Columns
        '    If lCol.ColumnName = "InvestorID" OrElse lCol.ColumnName = "FundID" Then Continue For
        '    If lCol.ColumnName.StartsWith(mstrSOFColPrefix) Then
        '        ldrAssociatedData.Item(lCol.ColumnName) = lblnIsSumOfFunds
        '    ElseIf lCol.ColumnName.EndsWith(mstrFormulaColSuffix) Then
        '        ldrAssociatedData.Item(lCol.ColumnName) = lstrActiveColName
        '    End If
        'Next
        ldtTargetData.Rows.Add(ldrAssociatedData)
        ldtTargetData.AcceptChanges()
    End Sub

    Private Function CheckSumOfFunds(ByVal pintInvestorID As Integer, ByVal lstrActiveColName As String, ByVal pblnAddMissing As Boolean, _
                                     ByVal pblnIsNullToTrue As Boolean) As Boolean
        Dim lblnIsSumOfFunds As Boolean = False
        Dim ldtTargetData As DataTable = Nothing
        Dim ldrAssociatedData As DataRow = Nothing
        Dim lblnCanCallFLData As Boolean = False
        Dim lobjPreviousProject As PreviousProjects = Nothing
        Dim lintListingID As Integer = 0
        Dim lobjListingInformation As ListingInformation = Nothing
        Dim lobjCurrentDataSources As CurrentDataSources = Nothing
        Dim lintEntityID As Integer = 0
        Dim lstrFormula As String = ""
        Try
            'Check if the currently selected column supports SOF column
            If mstEditableDataSourceNameCols.Contains(lstrActiveColName) Then
                If menmScreenType = DataHubScreenType.FinalizeList AndAlso mdtDEAssociatedData Is Nothing Then
                    mdtDEAssociatedData = New DataTable
                    AddMissingInvestorFundCols(mdtDEAssociatedData)
                    SetPrimaryKey(mdtDEAssociatedData)
                End If
                ldtTargetData = mdtDEAssociatedData
            ElseIf marrPreviousProjects.Contains(lstrActiveColName) OrElse lstrActiveColName.StartsWith(mstrCurrentListingColPrefix) Then
                ldtTargetData = mdtFLAssociatedData
                lblnCanCallFLData = True
            End If

            If ldtTargetData IsNot Nothing Then
                'Check the SumOfFunds of the selected column
                ldrAssociatedData = ldtTargetData.Rows.Find(New Object() {pintInvestorID, 0})
                If ldrAssociatedData Is Nothing OrElse ldtTargetData.Columns.Contains(mstrSOFColPrefix + lstrActiveColName) = False Then
                    If menmScreenType = DataHubScreenType.FinalizeList Then
                        If ldtTargetData.Columns.Contains(mstrSOFColPrefix + lstrActiveColName) = False Then
                            ldtTargetData.Columns.Add(mstrSOFColPrefix + lstrActiveColName, GetType(Boolean))
                            ldtTargetData.Columns.Add(lstrActiveColName + mstrFormulaColSuffix, GetType(String))
                        End If
                        If lblnCanCallFLData Then
                            If lstrActiveColName.StartsWith(mstrCurrentListingColPrefix) Then
                                lobjListingInformation = mstListingInformation.Find(Function(p) p.CurrentListingName = lstrActiveColName)
                                If lobjListingInformation IsNot Nothing Then
                                    lintListingID = lobjListingInformation.ListingID
                                End If
                            Else
                                lobjPreviousProject = mstPreviousProjects.Find(Function(p) p.DeliveryListing = lstrActiveColName)
                                If lobjPreviousProject IsNot Nothing Then
                                    lintListingID = lobjPreviousProject.ListingID
                                End If
                            End If
                        Else
                            lobjCurrentDataSources = mstCurrentDataSources.Find(Function(p) p.SourceName = lstrActiveColName)
                            If lobjCurrentDataSources IsNot Nothing Then
                                lintEntityID = lobjCurrentDataSources.EntityID
                            End If
                        End If
                        mclsDataHubManager.GetSOFFormulaInListingForRecord(pintInvestorID, 0, lintListingID, lintEntityID, lstrFormula, lblnIsSumOfFunds)
                        If ldrAssociatedData Is Nothing Then
                            AddAssociatedRow(ldtTargetData, pintInvestorID, 0, lstrActiveColName, lblnIsSumOfFunds, lstrFormula)
                        Else
                            ldrAssociatedData.Item(mstrSOFColPrefix + lstrActiveColName) = lblnIsSumOfFunds
                            ldrAssociatedData.Item(lstrActiveColName + mstrFormulaColSuffix) = lstrFormula
                        End If
                    ElseIf pblnAddMissing Then
                        If ldrAssociatedData Is Nothing Then
                            AddAssociatedRow(ldtTargetData, pintInvestorID, 0, lstrActiveColName, True, "")
                        End If
                        lblnIsSumOfFunds = True
                    End If
                Else
                    If pblnIsNullToTrue AndAlso lstrActiveColName.StartsWith(mstrCurrentListingColPrefix) = False Then
                        lblnIsSumOfFunds = CommonCLL.IsNullToTrueForBool(ldrAssociatedData(mstrSOFColPrefix + lstrActiveColName))
                    Else
                        lblnIsSumOfFunds = CommonCLL.IsNullToFalseForBool(ldrAssociatedData(mstrSOFColPrefix + lstrActiveColName))
                    End If
                End If
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            ldrAssociatedData = Nothing
            lobjPreviousProject = Nothing
            lobjCurrentDataSources = Nothing
            ldtTargetData = Nothing
        End Try
        Return lblnIsSumOfFunds
    End Function

    Private Function GetFormula(ByVal pintInvestorID As Integer, ByVal pintFundID As Integer, ByVal pintLinkID As Integer, ByVal lstrActiveColName As String, ByVal pblnAddMissing As Boolean) As String
        Dim lstrFormula As String = ""
        Dim ldtTargetData As DataTable = Nothing
        Dim ldrAssociatedData As DataRow = Nothing
        Dim lblnCanCallFLData As Boolean = False
        Dim lblnSOFValue As Boolean = True
        Dim lobjPreviousProject As PreviousProjects = Nothing
        Dim lobjListingInformation As ListingInformation = Nothing
        Dim lobjCurrentDataSources As CurrentDataSources = Nothing
        Dim lintListingID As Integer = 0
        Dim lintEntityID As Integer = 0
        Try
            'Check if the currently selected column supports Formula column
            If mstEditableDataSourceNameCols.Contains(lstrActiveColName) Then
                If menmScreenType = DataHubScreenType.FinalizeList AndAlso mdtDEAssociatedData Is Nothing Then
                    mdtDEAssociatedData = New DataTable
                    AddMissingInvestorFundCols(mdtDEAssociatedData)
                    SetPrimaryKey(mdtDEAssociatedData)
                End If
                ldtTargetData = mdtDEAssociatedData
            ElseIf marrPreviousProjects.Contains(lstrActiveColName) OrElse lstrActiveColName.StartsWith(mstrCurrentListingColPrefix) Then
                ldtTargetData = mdtFLAssociatedData
                lblnCanCallFLData = True
            End If
            If ldtTargetData IsNot Nothing Then
                'Check the SumOfFunds of the selected column
                ldrAssociatedData = ldtTargetData.Rows.Find(New Object() {pintInvestorID, pintFundID})
                If ldrAssociatedData Is Nothing OrElse ldtTargetData.Columns.Contains(mstrSOFColPrefix + lstrActiveColName) = False Then
                    If menmScreenType = DataHubScreenType.FinalizeList Then
                        If ldtTargetData.Columns.Contains(lstrActiveColName + mstrFormulaColSuffix) = False Then
                            ldtTargetData.Columns.Add(lstrActiveColName + mstrFormulaColSuffix, GetType(String))
                            ldtTargetData.Columns.Add(mstrSOFColPrefix + lstrActiveColName, GetType(Boolean))
                        End If
                        If lblnCanCallFLData Then
                            If lstrActiveColName.StartsWith(mstrCurrentListingColPrefix) Then
                                lobjListingInformation = mstListingInformation.Find(Function(p) p.CurrentListingName = lstrActiveColName)
                                If lobjListingInformation IsNot Nothing Then
                                    lintListingID = lobjListingInformation.ListingID
                                End If
                            Else
                                lobjPreviousProject = mstPreviousProjects.Find(Function(p) p.DeliveryListing = lstrActiveColName)
                                If lobjPreviousProject IsNot Nothing Then
                                    lintListingID = lobjPreviousProject.ListingID
                                End If
                            End If
                        Else
                            lobjCurrentDataSources = mstCurrentDataSources.Find(Function(p) p.SourceName = lstrActiveColName)
                            If lobjCurrentDataSources IsNot Nothing Then
                                lintEntityID = lobjCurrentDataSources.EntityID
                            End If
                        End If
                        mclsDataHubManager.GetSOFFormulaInListingForRecord(pintInvestorID, pintLinkID, lintListingID, lintEntityID, lstrFormula, lblnSOFValue)
                        If ldrAssociatedData Is Nothing Then
                            AddAssociatedRow(ldtTargetData, pintInvestorID, pintFundID, lstrActiveColName, lblnSOFValue, lstrFormula)
                        Else
                            ldrAssociatedData.Item(mstrSOFColPrefix + lstrActiveColName) = lblnSOFValue
                            ldrAssociatedData.Item(lstrActiveColName + mstrFormulaColSuffix) = lstrFormula
                        End If
                    ElseIf menmScreenType = DataHubScreenType.DataEntry AndAlso pblnAddMissing Then
                        If ldrAssociatedData Is Nothing Then
                            AddAssociatedRow(ldtTargetData, pintInvestorID, pintFundID, lstrActiveColName, True, "")
                        End If
                    End If
                Else
                    lstrFormula = ldrAssociatedData(lstrActiveColName + mstrFormulaColSuffix).ToString
                End If
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            lobjListingInformation = Nothing
            ldrAssociatedData = Nothing
            lobjPreviousProject = Nothing
            lobjCurrentDataSources = Nothing
            ldtTargetData = Nothing
        End Try
        Return lstrFormula
    End Function

    Private Sub SetAssociatedIsSumOfFunds(ByVal pintInvestorID As Integer, ByVal pintFundID As Integer, ByVal lstrActiveColName As String, ByVal pblnIsSumOfFunds As Boolean)
        Dim ldrAssociatedRow As DataRow = Nothing
        Dim ldtTargetData As DataTable = Nothing
        Dim ldrAssociatedData As DataRow = Nothing
        'Check if its a Data Source OR Previous Listing column
        If mstEditableDataSourceNameCols.Contains(lstrActiveColName) Then
            ldtTargetData = mdtDEAssociatedData
        ElseIf marrPreviousProjects.Contains(lstrActiveColName) OrElse lstrActiveColName.StartsWith(mstrCurrentListingColPrefix) Then
            ldtTargetData = mdtFLAssociatedData
        End If
        If ldtTargetData IsNot Nothing Then
            'Get the corresponding datarow
            ldrAssociatedData = ldtTargetData.Rows.Find(New Object() {pintInvestorID, pintFundID})
            If ldrAssociatedData Is Nothing Then
                AddAssociatedRow(ldtTargetData, pintInvestorID, pintFundID, lstrActiveColName, pblnIsSumOfFunds, "")
            Else
                ldrAssociatedData.Item(mstrSOFColPrefix + lstrActiveColName) = pblnIsSumOfFunds
            End If
            ldtTargetData.AcceptChanges()
        End If
    End Sub

    Private Sub SetAssociatedFormula(ByVal pintInvestorID As Integer, ByVal pintFundID As Integer, ByVal lstrActiveColName As String, ByVal pstrFormula As String)
        Dim ldrAssociatedRow As DataRow = Nothing
        Dim ldtTargetData As DataTable = Nothing
        Dim ldrAssociatedData As DataRow = Nothing
        'Check if its a Data Source OR Previous Listing column
        If mstEditableDataSourceNameCols.Contains(lstrActiveColName) Then
            ldtTargetData = mdtDEAssociatedData
        ElseIf marrPreviousProjects.Contains(lstrActiveColName) OrElse lstrActiveColName.StartsWith(mstrCurrentListingColPrefix) Then
            ldtTargetData = mdtFLAssociatedData
        End If
        If ldtTargetData IsNot Nothing Then
            'Get the corresponding datarow
            ldrAssociatedData = ldtTargetData.Rows.Find(New Object() {pintInvestorID, pintFundID})
            If ldrAssociatedData Is Nothing Then
                AddAssociatedRow(ldtTargetData, pintInvestorID, pintFundID, lstrActiveColName, True, pstrFormula)
            Else
                If ldrAssociatedData.Table.Columns.Contains(lstrActiveColName + mstrFormulaColSuffix) Then
                    ldrAssociatedData.Item(lstrActiveColName + mstrFormulaColSuffix) = pstrFormula
                End If
            End If
            ldtTargetData.AcceptChanges()
        End If
    End Sub

    'Private Function CheckSumOfFunds(ByVal pintInvestorRowIndex As Integer, ByVal lstrActiveColName As String) As Boolean
    '    Dim lblnIsSumOfFunds As Boolean
    '    'Check if the currently selected column supports SOF column
    '    If mdtFLAssociatedData.Columns.Contains(mstrSOFColPrefix + lstrActiveColName) Then
    '        'Check the SumOfFunds of the selected column
    '        lblnIsSumOfFunds = CommonCLL.IsNullToTrueForBool(grdData.Rows(pintInvestorRowIndex).GetCellValue(mstrSOFColPrefix + lstrActiveColName))
    '    Else
    '        lblnIsSumOfFunds = False
    '    End If
    '    Return lblnIsSumOfFunds
    'End Function

    ''' <summary>
    ''' To set the Investor and Managed Fund positions for the passed Investor and it's rows
    ''' </summary>
    ''' <param name="pintCalculatingRow">The row whose corresponding Investor's Sum to be calculated</param>
    ''' <param name="pstrColName">The column name being checked</param>
    ''' <remarks></remarks>
    Private Function CalculateSumOfFundPositions(ByVal pintCalculatingRow As Integer, ByVal pstrColName As String, ByVal pblnIsManagedFundExcluded As Boolean) As Int64
        Dim lintSum As Integer = 0
        Dim lintRowCounter As Integer = pintCalculatingRow
        Dim lugrWorkingRow As UltraGridRow = grdData.Rows(lintRowCounter)
        Try
            'The following code calculates the value of all associated Non-Managed fund's positions so that the position of Investor and the sum of Non-Managed Funds
            'can be compared.
            'This while loop starts from the selected row and goes upward till it's investor row
            While lintRowCounter >= 0
                'If the loop reaches to the Investor Row, then save it's text value in a variable
                If lugrWorkingRow.GetCellValue("LinkID") = 0 Then
                    Exit While
                End If

                'If the value is blank OR if it's a Cut row OR it's an ND OR it's a Managed Fund, then don't consider it's value in calculation of the Investor position
                If (lugrWorkingRow.GetCellValue("IsManaged") = True AndAlso pblnIsManagedFundExcluded) OrElse lugrWorkingRow.GetCellValue(pstrColName).ToString.Equals("") OrElse lugrWorkingRow.GetCellValue(pstrColName).ToString.Equals(mstrNDValue) Then
                    lintRowCounter -= 1
                    If lintRowCounter < 0 Then Exit While
                    lugrWorkingRow = grdData.Rows(lintRowCounter)
                    Continue While
                End If
                'Adding the fund's positions in a variable to formulate Investor's positions
                lintSum += lugrWorkingRow.GetCellValue(pstrColName)
                lintRowCounter -= 1
                If lintRowCounter < 0 Then Exit While
                lugrWorkingRow = grdData.Rows(lintRowCounter)
            End While

            'This while loop starts from the row next to the currently selected row and goes downward till it's last associated fund row
            lintRowCounter = pintCalculatingRow + 1
            If lintRowCounter < grdData.Rows.Count Then
                lugrWorkingRow = grdData.Rows(lintRowCounter)
                While lintRowCounter < grdData.Rows.Count And lugrWorkingRow.GetCellValue("LinkID") <> 0
                    'If the value is blank OR if it's a Cut row OR it's an ND OR it's a Managed Fund, then don't consider it's value in calculation of the Investor position
                    If lugrWorkingRow.GetCellValue("IsManaged") = True OrElse lugrWorkingRow.GetCellValue(pstrColName).ToString.Equals("") OrElse lugrWorkingRow.GetCellValue(pstrColName).ToString.Equals(mstrNDValue) Then
                        lintRowCounter += 1
                        If lintRowCounter = grdData.Rows.Count Then Exit While
                        lugrWorkingRow = grdData.Rows(lintRowCounter)
                        Continue While
                    End If
                    lintSum += lugrWorkingRow.GetCellValue(pstrColName).ToString
                    lintRowCounter += 1
                    If lintRowCounter = grdData.Rows.Count Then Exit While
                    lugrWorkingRow = grdData.Rows(lintRowCounter)
                End While
            End If
            Return lintSum
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
            Return 0
        Finally
            lugrWorkingRow = Nothing
        End Try
    End Function

    ''' <summary>
    ''' Check if the given value has a formula by checking the operators
    ''' </summary>
    ''' <param name="lstrActiveCellValue"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function HasFormulas(ByVal lstrActiveCellValue As String) As Boolean
        Dim lblnStatus As Boolean = False
        If CommonCLL.CountCharacter(lstrActiveCellValue, "+") = 1 Then
            If lstrActiveCellValue.StartsWith("+") = False Then lblnStatus = True
        ElseIf CommonCLL.CountCharacter(lstrActiveCellValue, "-") = 1 Then
            If lstrActiveCellValue.StartsWith("-") = False Then lblnStatus = True
        ElseIf (CommonCLL.CountCharacter(lstrActiveCellValue, "+") > 1 OrElse CommonCLL.CountCharacter(lstrActiveCellValue, "-") > 1) Then
            lblnStatus = True
        End If
        Return lblnStatus
    End Function

    ''' <summary>
    ''' Check if the value of the given cell is invalid
    ''' </summary>
    ''' <param name="lUltraRow">Given row</param>
    ''' <param name="pblnIsFromColumnList">Is From Column List form</param>
    ''' <param name="pstrDataSourceName">The column to be checked</param>
    ''' <param name="pblnIsInvalidValue">Results</param>
    ''' <remarks></remarks>
    Public Sub CheckInvalidValue(ByVal lUltraRow As UltraGridRow, ByVal pblnIsFromColumnList As Boolean, ByVal pstrDataSourceName As String, ByRef pblnIsInvalidValue As Boolean)
        Dim lintColCounter As Integer = 0
        Dim lblnIsSOFExists As Boolean = False
        Dim lblnIsFormulaExists As Boolean = False
        Dim lblnIsManual As Boolean = False
        Dim lblnCanAccessDelete As Boolean = True
        Dim lblnLoopStatus As Boolean = True
        Dim lultraIterativeRow As UltraGridRow = Nothing
        Try
            While lblnLoopStatus
                For Each lRow As UltraGridRow In grdData.Rows
                    'Set the row to be worked upon
                    If pblnIsFromColumnList Then
                        lultraIterativeRow = lRow
                    Else
                        lultraIterativeRow = lUltraRow
                    End If
                    'Check if value of all the data sources in the given row contains valid value
                    While lintColCounter < mstCurrentDataSources.Count
                        'If its from Column List then check only the given Data Source
                        If pblnIsFromColumnList Then
                            If mstCurrentDataSources.Item(lintColCounter).SourceName <> pstrDataSourceName Then
                                lintColCounter += 1
                                Continue While
                            End If
                        End If

                        'In some scenarios, 0 is considered as a valid value. e.g. Check if it has 0 position and Source is one from the following: Updates, DD Questions, 
                        'DD Client Emails, Research, Public
                        If lultraIterativeRow.GetCellValue(mstCurrentDataSources.Item(lintColCounter).SourceName).ToString.Equals("0") Then
                            'Check if there is a SOF column for the given column
                            If mstEditableDataSourceNameCols.Contains(mstCurrentDataSources.Item(lintColCounter).SourceName) Then
                                lblnIsSOFExists = True
                                'Check if there is a Formula column for the given column
                            ElseIf mstEditableDataSourceNameCols.Contains(mstCurrentDataSources.Item(lintColCounter).SourceName) Then
                                lblnIsFormulaExists = True
                            End If

                            'If SOF column exists
                            If lblnIsSOFExists Then
                                'And its SOF value is zero, then set it the boolean variable to False
                                If CheckSumOfFunds(lultraIterativeRow.GetCellValue("InvestorID"), mstCurrentDataSources.Item(lintColCounter).SourceName, False, False).ToString.Equals("1") = False Then
                                    lblnIsManual = True
                                End If
                            End If

                            'Check if it's not Sum Of Fund but its a formula
                            If lblnIsManual = False AndAlso lblnIsFormulaExists = True Then
                                If GetFormula(lultraIterativeRow.GetCellValue("InvestorID"), lultraIterativeRow.GetCellValue("FundID"), lultraIterativeRow.GetCellValue("LinkID"), mstCurrentDataSources.Item(lintColCounter).SourceName, False).ToString.Equals("") = False Then
                                    lblnIsManual = True
                                End If
                            End If

                            If lultraIterativeRow.GetCellValue("LinkID").Equals(0) = False Then
                                lblnIsManual = True
                            End If
                            'If the position is 0 and it's manual, then it's a valid value for the following sources
                            If lblnIsManual Then
                                If mstCurrentDataSources.Item(lintColCounter).SourceTypeCode.Equals(SourceTypeCode.UPD.ToString) OrElse _
                                    (mstCurrentDataSources.Item(lintColCounter).SourceTypeCode.Equals(SourceTypeCode.DDI.ToString) AndAlso _
                                     (mstCurrentDataSources.Item(lintColCounter).ESourceCode.Equals(DataSourceCode.DDCLEML.ToString) OrElse _
                                      mstCurrentDataSources.Item(lintColCounter).ESourceCode.Equals(DataSourceCode.DDQUEST.ToString)) _
                                        ) OrElse _
                                    mstCurrentDataSources.Item(lintColCounter).SourceTypeCode.Equals(SourceTypeCode.RSH.ToString) OrElse _
                                    mstCurrentDataSources.Item(lintColCounter).SourceTypeCode.Equals(SourceTypeCode.PBC.ToString) Then
                                    lblnCanAccessDelete = False
                                    pblnIsInvalidValue = False
                                    Exit Sub
                                End If
                            End If
                            'Otherwise, check if it has any data source which does not contain blank then its considered as a valid value
                        ElseIf lultraIterativeRow.GetCellValue(mstCurrentDataSources.Item(lintColCounter).SourceName).ToString.Equals("") = False Then
                            lblnCanAccessDelete = False
                            pblnIsInvalidValue = False
                            Exit Sub
                        End If
                        lintColCounter += 1
                    End While
                    'If its coming from ColumnList form, then the loop has to run only once
                    If pblnIsFromColumnList = False Then
                        lblnLoopStatus = False
                        Exit For
                    End If
                Next
                lblnLoopStatus = False
            End While
            'If it's NOT coming from ColumnList form, then check if any of the previous project position has a non-blank, non-zero value, if so, consider it as a valid value
            If pblnIsFromColumnList = False Then
                lintColCounter = 0
                While lintColCounter < marrPreviousProjects.Length
                    If lUltraRow.GetCellValue(marrPreviousProjects(lintColCounter)).ToString.Equals("") = False AndAlso lUltraRow.GetCellValue(marrPreviousProjects(lintColCounter)).ToString.Equals("0") = False Then
                        lblnCanAccessDelete = False
                        pblnIsInvalidValue = False
                        Exit Sub
                    End If
                    lintColCounter += 1
                End While
            End If
            pblnIsInvalidValue = True
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            lultraIterativeRow = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' To focus on the first locked cell or InvestorName column
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub FocusOnFirstLockedCell(ByVal pblnCanSelect0thRow As Boolean)
        Dim lintColCounter As Integer = mintParentIndex
        Dim lobjLockedRow As CurrentDataSources = Nothing
        Dim lintColIndex As Integer = -1
        Dim lstrFirstLockedCol As String = ""
        Dim lugrFirstVisibleRow As UltraGridRow
        Dim lstrWorkingCol As String = ""
        Try
            If menmScreenType = DataHubScreenType.FinalizeList Then
                Dim lintActiveRowVisibleRowIndex As Integer = grdData.ActiveCell.Row.VisibleIndex
                Dim lintFirstVisibleRowIndex As Integer = grdData.ActiveRowScrollRegion.VisibleRows(0).Row.Index
                Dim lintLastVisibleRowIndex As Integer = grdData.ActiveRowScrollRegion.VisibleRows(grdData.DisplayLayout.RowScrollRegions(0).VisibleRows.Count - 1).Row.Index
                If lintActiveRowVisibleRowIndex >= lintFirstVisibleRowIndex AndAlso lintActiveRowVisibleRowIndex <= lintLastVisibleRowIndex Then
                    grdData.Focus()
                    grdData.ActiveColScrollRegion.ScrollColIntoView(grdData.DisplayLayout.Bands(0).Columns("Current ORD"))
                Else
                    If grdData.Selected.Cells.Count = 1 Then
                        grdData.Selected.Cells(0).Selected = False
                    End If
                    grdData.Focus()
                    Dim lobjListingInformation As ListingInformation = Nothing
                    Dim lstrPrimaryListingName As String = ""
                    lobjListingInformation = mstListingInformation.Find(Function(p) p.ListingName = "ORD")
                    If lobjListingInformation Is Nothing Then
                        lstrPrimaryListingName = mstListingInformation(0).CurrentListingName
                    Else
                        lstrPrimaryListingName = lobjListingInformation.CurrentListingName
                    End If
                    grdData.ActiveColScrollRegion.ScrollColIntoView(grdData.DisplayLayout.Bands(0).Columns(lstrPrimaryListingName))
                    grdData.DisplayLayout.RowScrollRegions(0).VisibleRows(0).Row.Cells(lstrPrimaryListingName).Activated = True
                    grdData.DisplayLayout.RowScrollRegions(0).VisibleRows(0).Row.Cells(lstrPrimaryListingName).Selected = True
                    'grdData.DisplayLayout.RowScrollRegions(0).VisibleRows(0).Row.
                End If
                'grdData.DisplayLayout.RowScrollRegions(0).VisibleRows(0).Row
            Else
                'Find out the locked column
                While lintColCounter < grdData.Rows.Band.Columns.Count
                    If mstEditableDataSourceNameCols.Contains(grdData.Rows.Band.Columns(lintColCounter).Header.Caption) Then
                        lobjLockedRow = mstCurrentDataSources.Find(Function(p) p.SourceName = grdData.Rows.Band.Columns(lintColCounter).Header.Caption)
                        If lobjLockedRow.AccessStatus = SourceAccessbility.Locked.ToString Then
                            lintColIndex = grdData.Rows.Band.Columns(lintColCounter).Index
                            lstrFirstLockedCol = grdData.Rows.Band.Columns(lintColCounter).Header.Caption
                            Exit While
                        End If
                    End If
                    lintColCounter += 1
                End While
                'Find out the first visible row

                If pblnCanSelect0thRow Then
                    lugrFirstVisibleRow = grdData.Rows(0)
                Else
                    lugrFirstVisibleRow = grdData.DisplayLayout.RowScrollRegions(0).VisibleRows(0).Row
                End If
                If lugrFirstVisibleRow IsNot Nothing Then
                    If lugrFirstVisibleRow.Index >= 0 Then
                        lugrFirstVisibleRow.Activated = True
                        lugrFirstVisibleRow.Selected = True
                        grdData.ActiveRowScrollRegion.ScrollRowIntoView(lugrFirstVisibleRow)
                    End If

                    'If there is a locked column, then focus on it
                    If lintColIndex <> -1 Then
                        lstrWorkingCol = lstrFirstLockedCol
                    ElseIf grdData.Rows.FirstVisibleCardRow.Index >= 0 Then
                        'Otherwise focus on the Name column
                        lstrWorkingCol = "Name"
                    End If

                    grdData.Focus()
                    grdData.ActiveColScrollRegion.ScrollColIntoView(grdData.DisplayLayout.Rows.Band.Columns(lstrWorkingCol), True)
                    grdData.DisplayLayout.Rows.Band.Columns(lstrWorkingCol).Header.Activated = True
                    For Each lSelectedCol As ColumnHeader In grdData.Selected.Columns
                        lSelectedCol.Selected = False
                    Next
                    grdData.DisplayLayout.Rows.Band.Columns(lstrWorkingCol).Header.Selected = False
                    lugrFirstVisibleRow.Cells(lstrWorkingCol).Activated = True
                    lugrFirstVisibleRow.Cells(lstrWorkingCol).Selected = True
                End If
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            lobjLockedRow = Nothing
            lugrFirstVisibleRow = Nothing
        End Try
    End Sub
#End Region

#Region "Preparation Procedures"

    ''' <summary>
    ''' To Initialize track change tables, Data Source Changes, Previous Project Changes, Linking Changes tables
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub InitializeChangeTrackTable()

    End Sub

    ''' <summary>
    ''' To make array of various useful entities which will be used for quick checks
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub PrepareDataSourceDetails()
        Dim lintArrColCount As Integer
        mstAllDataSourceNameCols = New List(Of String)
        mstEditableDataSourceNameCols = New List(Of String)
        'mstSOFCols = New List(Of String)
        mstSysColumns = New List(Of String)
        mstPublicFilingDateCols = New List(Of String)
        mstPublicSourcesCols = New List(Of String)
        mstResearchSourceCols = New List(Of String)
        mstResearchDateCols = New List(Of String)
        mstAllDataSourceDateCols = New List(Of String)
        mstDataSourceParentGroupDateCol = New List(Of String)
        mstDataSourceParentGroupPositionCol = New List(Of String)

        mstSysColumns.Add("UserID")
        mstSysColumns.Add("ProjectID")
        mstSysColumns.Add("IsMasterDB")
        mstSysColumns.Add("RowNumber")
        mstSysColumns.Add("DenseRank")
        mstSysColumns.Add("FundDenseRank")
        mstSysColumns.Add("InvestorID")
        mstSysColumns.Add("LinkID")
        mstSysColumns.Add("FundID")
        mstSysColumns.Add("IsInvestor")
        mstSysColumns.Add("IsManaged")
        mstSysColumns.Add("IsCutRow")
        mstSysColumns.Add("InvestorName")
        mstSysColumns.Add("FundName")
        mstSysColumns.Add("InvStatusCode")
        mstSysColumns.Add("MInvestorTypeID")

        'mstAttributeSet1 = New List(Of String)
        'mstAttributeSet1.Add("UserID")
        'mstAttributeSet1.Add("ProjectID")
        'mstAttributeSet1.Add("IsMasterDB")
        'mstAttributeSet1.Add("RowNumber")
        'mstAttributeSet1.Add("DenseRank")
        'mstAttributeSet1.Add("FundDenseRank")
        'mstAttributeSet1.Add("InvestorID")
        'mstAttributeSet1.Add("LinkID")
        'mstAttributeSet1.Add("FundID")
        'mstAttributeSet1.Add("IsInvestor")
        'mstAttributeSet1.Add("IsManaged")
        'mstAttributeSet1.Add("IsCutRow")
        'mstAttributeSet1.Add("Notes")
        'mstAttributeSet1.Add("Origin")
        'mstAttributeSet1.Add("InvestorName")
        'mstAttributeSet1.Add("FundName")
        'mstAttributeSet1.Add("ID")
        'mstAttributeSet1.Add("InvStatusCode")
        'mstAttributeSet1.Add("Status")
        'mstAttributeSet1.Add("Name")
        'mstAttributeSet1.Add("MInvestorTypeID")
        'mstAttributeSet1.Add("Head Investor")
        'mstAttributeSet1.Add("Parent")

        mstAttributeSet2 = New List(Of String)
        mstAttributeSet2.Add("Activist")
        mstAttributeSet2.Add("Type")
        mstAttributeSet2.Add("Style")
        mstAttributeSet2.Add("Turnover")
        mstAttributeSet2.Add("City")
        mstAttributeSet2.Add("State")
        mstAttributeSet2.Add("Country")
        mstAttributeSet2.Add("Region")

        For Each lobjCurrentDataSources As CurrentDataSources In mstCurrentDataSources
            mstAllDataSourceNameCols.Add(lobjCurrentDataSources.SourceName)
            'mstAllDataSourceNameCols(mstAllDataSourceNameCols.Length - 1) = lobjCurrentDataSources.SourceName
            If marrEditableSourceTypes.Contains(lobjCurrentDataSources.SourceTypeCode) Then
                'mstSOFCols.Add(mstrSOFColPrefix + lobjCurrentDataSources.SourceName)
                mstEditableDataSourceNameCols.Add(lobjCurrentDataSources.SourceName)
            End If
            If lobjCurrentDataSources.SourceDate.ToString.Equals("") = False Then
                mstAllDataSourceDateCols.Add(lobjCurrentDataSources.SourceDate.ToString)
                'mstAllDataSourceDateCols(mstAllDataSourceDateCols.Length - 1) = lobjCurrentDataSources.SourceDate.ToString
                'ReDim Preserve mstAllDataSourceDateCols(mstAllDataSourceDateCols.Length)
            End If
            'ReDim Preserve mstAllDataSourceNameCols(mstAllDataSourceNameCols.Length)
            lintArrColCount += 1

            If lobjCurrentDataSources.SourceTypeCode = SourceTypeCode.PBC.ToString Then
                mstPublicFilingDateCols.Add(lobjCurrentDataSources.PublicFilingDateCol)
                mstPublicSourcesCols.Add(lobjCurrentDataSources.PublicSourceCol)
            End If
            If lobjCurrentDataSources.SourceTypeCode = SourceTypeCode.RSH.ToString Then
                mstResearchSourceCols.Add(lobjCurrentDataSources.ResearchSourceCol)
                mstResearchDateCols.Add(lobjCurrentDataSources.SourceDate)
            End If
        Next
        'Array that contains names of all data sources of the current project
        'ReDim Preserve mstAllDataSourceNameCols(mstAllDataSourceNameCols.Length - 2)
        'Array that contains names of all editable data sources of the current project
        'ReDim Preserve marrEditableDataSourceNameCols(marrEditableDataSourceNameCols.Length - 2)
        'Array that contains EntityIDs of all editable data sources of the current project
        'ReDim Preserve marrEditableEntityIDs(marrEditableEntityIDs.Length - 2)
        'Array that contains names of all date enabled data sources of the current project
        'If mstAllDataSourceDateCols.Length > 0 Then
        '    ReDim Preserve mstAllDataSourceDateCols(mstAllDataSourceDateCols.Length - 2)
        'End If

        'For previous projects' data sources
        lintArrColCount = 0
        For Each lobjPreviousDataSources As PreviousDataSources In mstPreviousDataSources
            marrPreviousDataSourceNameCols(marrPreviousDataSourceNameCols.Length - 1) = lobjPreviousDataSources.SourceName
            If lobjPreviousDataSources.SourceDate.Equals("") = False Then
                marrPreviousSourceDateCols(marrPreviousSourceDateCols.Length - 1) = lobjPreviousDataSources.SourceDate
                ReDim Preserve marrPreviousSourceDateCols(marrPreviousSourceDateCols.Length)
            End If
            ReDim Preserve marrPreviousDataSourceNameCols(marrPreviousDataSourceNameCols.Length)
            lintArrColCount += 1
        Next
        If marrPreviousDataSourceNameCols.Length = 1 Then
            If marrPreviousDataSourceNameCols(0) Is Nothing Then
                'Array that contains names of all data sources of the previous most recent project
                ReDim Preserve marrPreviousDataSourceNameCols(marrPreviousDataSourceNameCols.Length - 1)
                'Array that contains names of all date enabled data sources of the previous most recent project
                ReDim Preserve marrPreviousSourceDateCols(marrPreviousSourceDateCols.Length - 1)
            End If
        Else
            'Array that contains names of all data sources of the previous most recent project
            ReDim Preserve marrPreviousDataSourceNameCols(marrPreviousDataSourceNameCols.Length - 2)
            'Array that contains names of all date enabled data sources of the previous most recent project
            ReDim Preserve marrPreviousSourceDateCols(marrPreviousSourceDateCols.Length - 2)
        End If

        'For previous projects' listings' data
        lintArrColCount = 0
        For Each lobjPreviousProjects As PreviousProjects In mstPreviousProjects
            marrPreviousProjects(marrPreviousProjects.Length - 1) = lobjPreviousProjects.DeliveryListing
            ReDim Preserve marrPreviousProjects(marrPreviousProjects.Length)
            lintArrColCount += 1
        Next
        'Array that contains names of all previous projects
        If marrPreviousProjects.Length > 0 Then
            ReDim Preserve marrPreviousProjects(marrPreviousProjects.Length - 2)
        End If
        For Each lobjListingInformation In mstListingInformation
            mstDataSourceParentGroupDateCol.Add(mstrUpdatesColPrefix + lobjListingInformation.ListingName + mstrSourceDateColSuffix)
            mstDataSourceParentGroupDateCol.Add(mstrDDInfoColPrefix + lobjListingInformation.ListingName + mstrSourceDateColSuffix)

            mstDataSourceParentGroupPositionCol.Add(mstrUpdatesColPrefix + lobjListingInformation.ListingName)
            mstDataSourceParentGroupPositionCol.Add(mstrDDInfoColPrefix + lobjListingInformation.ListingName)
            mstDataSourceParentGroupPositionCol.Add(mstrRegisterColPrefix + lobjListingInformation.ListingName)
            mstDataSourceParentGroupPositionCol.Add(mstrBanklistColPrefix + lobjListingInformation.ListingName)
        Next
    End Sub

    ''' <summary>
    ''' To set the date column as adjancent to it's parent column in the datatable, when data is fetched from database parent column and associated date column are not adjacent
    ''' </summary>
    ''' <param name="ldtData"></param>
    ''' <remarks></remarks>
    Private Sub SetGridDataColumnIndex(ByRef ldtData As DataTable)
        Dim lintColCounter As Integer = mintParentIndex + 1
        Dim lobjDataSource As CurrentDataSources = Nothing
        Dim lintArrColCount As Integer
        Dim larrExcludingCols(1) As String
        Dim lstrColName As New StringBuilder
        Dim lintParentIndex As Integer
        Dim lintPreviousProjectIndex As Integer
        Dim lstLastProjectListings As New List(Of String)
        Try
            lintParentIndex = ldtData.Columns("Parent").Ordinal
            While lintColCounter < ldtData.Columns.Count
                lstrColName.Remove(0, lstrColName.Length)
                lstrColName.Append(ldtData.Columns(lintColCounter).ColumnName)
                If larrExcludingCols.Contains(lstrColName.ToString) Then
                    lintColCounter += 1
                    Continue While
                End If
                'Check if the given column is data source column
                If mstAllDataSourceNameCols.Contains(lstrColName.ToString) Then
                    lobjDataSource = mstCurrentDataSources.Find(Function(p) p.SourceName = lstrColName.ToString)
                    If lobjDataSource IsNot Nothing Then
                        'Check if supports the date
                        If marrDateSuppertedSourceTypes.Contains(lobjDataSource.ESourceCode) AndAlso ldtData.Columns.Contains(lobjDataSource.SourceDate) Then
                            'If yes, then set the date column adjacent to the Source column
                            If ldtData.Columns(lobjDataSource.SourceDate).Ordinal < ldtData.Columns(lobjDataSource.SourceName).Ordinal Then
                                ldtData.Columns(lobjDataSource.SourceDate).SetOrdinal(lintColCounter)
                            Else
                                ldtData.Columns(lobjDataSource.SourceDate).SetOrdinal(lintColCounter + 1)
                            End If
                            'ldtData.Columns(lobjDataSource.SourceDate).SetOrdinal(lintColCounter + 1)
                            lintColCounter = lintParentIndex + 1
                            larrExcludingCols(lintArrColCount) = lobjDataSource.SourceName
                            ReDim Preserve larrExcludingCols(lintArrColCount + 1)
                            lintArrColCount += 1

                            'Check if it's Research column, set the Index of it's Source column
                            If lobjDataSource.SourceTypeCode = SourceTypeCode.RSH.ToString AndAlso ldtData.Columns.Contains(lobjDataSource.SourceName + mstrSourceColSuffix) Then
                                ldtData.Columns(lobjDataSource.SourceName + mstrSourceColSuffix).SetOrdinal(ldtData.Columns(lobjDataSource.SourceName).Ordinal + 2)
                            End If
                            Continue While
                        End If
                        'Check if it's Public column, set the Filing Date and Source column
                        If lobjDataSource.SourceTypeCode = SourceTypeCode.PBC.ToString Then
                            If ldtData.Columns.Contains(lobjDataSource.PublicFilingDateCol) Then
                                ldtData.Columns(lobjDataSource.PublicFilingDateCol).SetOrdinal(ldtData.Columns(lobjDataSource.SourceName).Ordinal + 1)
                                ldtData.Columns(lobjDataSource.PublicSourceCol).SetOrdinal(ldtData.Columns(lobjDataSource.SourceName).Ordinal + 2)
                            End If
                            If grdData.DataSource IsNot Nothing Then
                                If grdData.Rows.Band.Columns.Exists(lobjDataSource.PublicFilingDateCol) Then
                                    grdData.Rows.Band.Columns(lobjDataSource.PublicFilingDateCol).Header.VisiblePosition = grdData.Rows.Band.Columns(lobjDataSource.SourceName).Header.VisiblePosition + 1
                                    grdData.Rows.Band.Columns(lobjDataSource.PublicSourceCol).Header.VisiblePosition = grdData.Rows.Band.Columns(lobjDataSource.SourceName).Header.VisiblePosition + 2
                                End If
                            End If
                        End If
                    End If
                End If
                lintColCounter += 1
            End While
            ReDim Preserve larrExcludingCols(lintArrColCount - 1)
            lstrColName = Nothing

            lintPreviousProjectIndex = 0
            While lintPreviousProjectIndex < mstPreviousProjects.Count
                If ldtData.Columns.Contains(mstPreviousProjects(lintPreviousProjectIndex).DeliveryListing) Then
                    If ldtData.Columns(mstPreviousProjects(lintPreviousProjectIndex).DeliveryListing).Ordinal < ldtData.Columns("Activist").Ordinal Then
                        ldtData.Columns(mstPreviousProjects(lintPreviousProjectIndex).DeliveryListing).SetOrdinal(ldtData.Columns("Activist").Ordinal)
                    Else
                        ldtData.Columns(mstPreviousProjects(lintPreviousProjectIndex).DeliveryListing).SetOrdinal(ldtData.Columns("Activist").Ordinal + 1)
                    End If
                End If
                lintPreviousProjectIndex += 1
            End While
            'If mstPreviousProjects.Count > 0 Then
            '    lintPreviousProjectIndex = ldtData.Columns("Activist").Ordinal - 1
            '    lstLastProjectListings = mstAllPreviousListings.FindAll(Function(p) p.StartsWith(mstrPreviousProjectName))
            '    While lintPreviousProjectIndex >= 0
            '        If mstAllPreviousListings.Contains(ldtData.Columns(lintPreviousProjectIndex).ColumnName) = False Then
            '            Exit While
            '        End If
            '        lintPreviousProjectIndex -= 1
            '    End While
            '    lintPreviousProjectIndex += 1
            '    For Each lstrLastProjectListing As String In lstLastProjectListings
            '        ldtData.Columns(lstrLastProjectListing).SetOrdinal(lintPreviousProjectIndex)
            '    Next
            'End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            lstrColName = Nothing
            lobjDataSource = Nothing
            lstLastProjectListings = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' To set the placement of FL columns as per the requirement
    ''' </summary>
    ''' <param name="ldtData"></param>
    ''' <remarks></remarks>
    Private Sub SetGridDataFLColumnIndex(ByRef ldtData As DataTable)
        Dim lintColCounter As Integer = mintParentIndex + 1
        Dim lobjDataSource As CurrentDataSources = Nothing
        Dim lstCurrentDataSources As List(Of CurrentDataSources) = Nothing
        Dim lintArrColCount As Integer
        Dim lstExcludingCols As New List(Of String)
        Dim lstrColName As New StringBuilder
        Dim lintParentIndex As Integer
        Dim lintSuggestedFinalListingColIndex As Integer
        Dim lintSourceGroupStartingColIndex As Integer
        Dim lintSourceColCounter As Int16
        Dim lintTraversingListingID As Int16
        Dim lintSourceCounter As Int16
        Dim lintListingStartingIndex As Integer

        Dim lblnHasUpdates As Boolean = False
        Dim lblnHasDDInfo As Boolean = False
        Dim lblnHasDDAllocations As Boolean = False
        Dim lblnHasRegister As Boolean = False
        Dim lblnHasBanklist As Boolean = False
        Dim lblnHasResearch As Boolean = False
        Dim lblnHasPublic As Boolean = False
        Try
            ldtData.Columns("Parent").SetOrdinal(ldtData.Columns("Head Investor").Ordinal + 1)
            lintParentIndex = ldtData.Columns("Parent").Ordinal
            'To set the index/ordinal of the Parent Group columns
            For Each lobjListingInformation As ListingInformation In mstListingInformation
                lintSourceColCounter = 0
                lintSourceGroupStartingColIndex = 0
                If lobjListingInformation.ListingID = mstListingInformation(0).ListingID Then
                    lintListingStartingIndex = lintParentIndex
                End If
                ldtData.Columns(mstrCurrentListingColPrefix + lobjListingInformation.ListingName).SetOrdinal(lintListingStartingIndex + 1)
                'ldtData.Columns(mstrSuggestedFinalListingColPrefix + lobjListingInformation.ListingName).SetOrdinal(ldtData.Columns(mstrCurrentListingColPrefix + lobjListingInformation.ListingName).Ordinal + 1)
                If ldtData.Columns(mstrSuggestedFinalListingColPrefix + lobjListingInformation.ListingName).Ordinal < ldtData.Columns(mstrCurrentListingColPrefix + lobjListingInformation.ListingName).Ordinal Then
                    ldtData.Columns(mstrSuggestedFinalListingColPrefix + lobjListingInformation.ListingName).SetOrdinal(lintListingStartingIndex)
                Else
                    ldtData.Columns(mstrSuggestedFinalListingColPrefix + lobjListingInformation.ListingName).SetOrdinal(lintListingStartingIndex + 1)
                End If
                lintTraversingListingID = lobjListingInformation.ListingID

                lintSuggestedFinalListingColIndex = ldtData.Columns(mstrCurrentListingColPrefix + lobjListingInformation.ListingName).Ordinal

                lstCurrentDataSources = mstCurrentDataSources.FindAll(Function(p) p.SourceTypeCode = SourceTypeCode.UPD.ToString AndAlso p.ListingID = lintTraversingListingID)
                If lstCurrentDataSources.Count > 0 Then
                    lblnHasUpdates = True
                    lintSourceCounter = 2
                    lintSourceGroupStartingColIndex = lintSuggestedFinalListingColIndex + 1
                    ldtData.Columns(mstrUpdatesColPrefix + lobjListingInformation.ListingName).SetOrdinal(lintSourceGroupStartingColIndex)
                    ldtData.Columns(mstrUpdatesColPrefix + lobjListingInformation.ListingName + mstrSourceDateColSuffix).SetOrdinal(lintSourceGroupStartingColIndex + 1)
                    lintSourceGroupStartingColIndex = lintSourceGroupStartingColIndex + lintSourceCounter
                End If

                lstCurrentDataSources = mstCurrentDataSources.FindAll(Function(p) (p.ESourceCode = DataSourceCode.DDCLEML.ToString OrElse p.ESourceCode = DataSourceCode.DDQUEST.ToString) _
                                                                          AndAlso p.ListingID = lintTraversingListingID)
                If lstCurrentDataSources.Count > 0 Then
                    lblnHasDDInfo = True
                    'lintSourceGroupStartingColIndex = lintSourceGroupStartingColIndex + lintSourceCounter
                    If lintSourceGroupStartingColIndex = 0 Then
                        lintSourceGroupStartingColIndex = lintSuggestedFinalListingColIndex + 1
                    End If
                    lintSourceCounter = 2
                    ldtData.Columns(mstrDDInfoColPrefix + lobjListingInformation.ListingName).SetOrdinal(lintSourceGroupStartingColIndex)
                    ldtData.Columns(mstrDDInfoColPrefix + lobjListingInformation.ListingName + mstrSourceDateColSuffix).SetOrdinal(lintSourceGroupStartingColIndex + 1)
                    lintSourceGroupStartingColIndex = lintSourceGroupStartingColIndex + lintSourceCounter
                End If

                lstCurrentDataSources = mstCurrentDataSources.FindAll(Function(p) (p.SourceTypeCode = SourceTypeCode.REG.ToString OrElse _
                                                                                                    p.SourceTypeCode = SourceTypeCode.RGT.ToString) AndAlso _
                                                                                                p.ListingID = lintTraversingListingID)
                If lstCurrentDataSources.Count > 0 Then
                    lblnHasRegister = True
                    'lintSourceGroupStartingColIndex = lintSourceGroupStartingColIndex + lintSourceCounter
                    If lintSourceGroupStartingColIndex = 0 Then
                        lintSourceGroupStartingColIndex = lintSuggestedFinalListingColIndex + 1
                    End If
                    lintSourceCounter = 1
                    ldtData.Columns(mstrRegisterColPrefix + lobjListingInformation.ListingName).SetOrdinal(lintSourceGroupStartingColIndex)
                    lintSourceGroupStartingColIndex = lintSourceGroupStartingColIndex + lintSourceCounter
                End If

                lstCurrentDataSources = mstCurrentDataSources.FindAll(Function(p) (p.SourceTypeCode = SourceTypeCode.BKL.ToString OrElse _
                                                                                  p.SourceTypeCode = SourceTypeCode.PRB.ToString OrElse _
                                                                                  p.SourceTypeCode = SourceTypeCode.EPB.ToString OrElse _
                                                                                  p.SourceTypeCode = SourceTypeCode.EBL.ToString) AndAlso _
                                                                                p.ListingID = lintTraversingListingID)
                If lstCurrentDataSources.Count > 0 Then
                    lblnHasBanklist = True
                    'lintSourceGroupStartingColIndex = lintSourceGroupStartingColIndex + lintSourceCounter
                    If lintSourceGroupStartingColIndex = 0 Then
                        lintSourceGroupStartingColIndex = lintSuggestedFinalListingColIndex + 1
                    End If
                    lintSourceCounter = 1
                    ldtData.Columns(mstrBanklistColPrefix + lobjListingInformation.ListingName).SetOrdinal(lintSourceGroupStartingColIndex)
                    lintSourceGroupStartingColIndex = lintSourceGroupStartingColIndex + lintSourceCounter
                End If

                If ldtData.Columns.Contains(mstrPreviousProjectName + " " + lobjListingInformation.ListingName) Then
                    'lintListingStartingIndex += 1
                    If lintSourceGroupStartingColIndex = 0 Then
                        lintSourceGroupStartingColIndex = lintSuggestedFinalListingColIndex + 1
                    End If
                    ldtData.Columns(mstrPreviousProjectName + " " + lobjListingInformation.ListingName).SetOrdinal(lintSourceGroupStartingColIndex)
                    lintSourceGroupStartingColIndex = lintSourceGroupStartingColIndex + 1
                End If

                If lintSourceGroupStartingColIndex = 0 Then
                    lintListingStartingIndex = ldtData.Columns(mstrCurrentListingColPrefix + lobjListingInformation.ListingName).Ordinal
                Else
                    lintListingStartingIndex = lintSourceGroupStartingColIndex - 1
                End If
                'lintListingStartingIndex = lintSourceGroupStartingColIndex + lintSourceColCounter
            Next

            lintSourceGroupStartingColIndex = 0
            For Each lobjListingInformation As ListingInformation In mstListingInformation
                lintTraversingListingID = lobjListingInformation.ListingID
                lintSourceGroupStartingColIndex = ldtData.Columns(mstrCurrentListingColPrefix + lobjListingInformation.ListingName).Ordinal + 1

                If lblnHasUpdates Then
                    lintSourceGroupStartingColIndex += 2
                    lstCurrentDataSources = mstCurrentDataSources.FindAll(Function(p) p.SourceTypeCode = SourceTypeCode.UPD.ToString AndAlso p.ListingID = lintTraversingListingID)
                    If lstCurrentDataSources.Count > 0 Then
                        lintSourceColCounter = 0
                        While lintSourceColCounter < lstCurrentDataSources.Count
                            'lintSourceCounter += 1
                            If ldtData.Columns(lstCurrentDataSources(lintSourceColCounter).SourceName).Ordinal < lintSourceGroupStartingColIndex + lintSourceColCounter Then
                                ldtData.Columns(lstCurrentDataSources(lintSourceColCounter).SourceName).SetOrdinal(lintSourceGroupStartingColIndex + lintSourceColCounter - 1)
                            Else
                                ldtData.Columns(lstCurrentDataSources(lintSourceColCounter).SourceName).SetOrdinal(lintSourceGroupStartingColIndex + lintSourceColCounter)
                            End If
                            lintSourceColCounter += 1
                        End While
                        lintSourceGroupStartingColIndex = ldtData.Columns(mstrUpdatesColPrefix + lobjListingInformation.ListingName + mstrSourceDateColSuffix).Ordinal + lstCurrentDataSources.Count + 1
                    End If
                End If

                If lblnHasDDInfo Then
                    lintSourceGroupStartingColIndex += 2
                    lstCurrentDataSources = mstCurrentDataSources.FindAll(Function(p) (p.ESourceCode = DataSourceCode.DDCLEML.ToString OrElse p.ESourceCode = DataSourceCode.DDQUEST.ToString) _
                                                                          AndAlso p.ListingID = lintTraversingListingID)
                    If lstCurrentDataSources.Count > 0 Then
                        lintSourceColCounter = 0
                        While lintSourceColCounter < lstCurrentDataSources.Count
                            'lintSourceCounter += 1
                            If ldtData.Columns(lstCurrentDataSources(lintSourceColCounter).SourceName).Ordinal < lintSourceGroupStartingColIndex + lintSourceColCounter Then
                                ldtData.Columns(lstCurrentDataSources(lintSourceColCounter).SourceName).SetOrdinal(lintSourceGroupStartingColIndex + lintSourceColCounter - 1)
                            Else
                                ldtData.Columns(lstCurrentDataSources(lintSourceColCounter).SourceName).SetOrdinal(lintSourceGroupStartingColIndex + lintSourceColCounter)
                            End If
                            lintSourceColCounter += 1
                        End While
                        lintSourceGroupStartingColIndex = ldtData.Columns(mstrDDInfoColPrefix + lobjListingInformation.ListingName + mstrSourceDateColSuffix).Ordinal + lstCurrentDataSources.Count + 1
                    End If
                End If

                'If lblnHasDDAllocations Then
                lstCurrentDataSources = mstCurrentDataSources.FindAll(Function(p) (p.ESourceCode = DataSourceCode.DDALCOT.ToString OrElse p.ESourceCode = DataSourceCode.EDDALOT.ToString) AndAlso _
                                                                            p.ListingID = lintTraversingListingID)
                If lstCurrentDataSources.Count > 0 Then
                    lintSourceColCounter = 0
                    While lintSourceColCounter < lstCurrentDataSources.Count
                        'lintSourceCounter += 1
                        If ldtData.Columns(lstCurrentDataSources(lintSourceColCounter).SourceName).Ordinal < lintSourceGroupStartingColIndex + lintSourceColCounter Then
                            ldtData.Columns(lstCurrentDataSources(lintSourceColCounter).SourceName).SetOrdinal(lintSourceGroupStartingColIndex + lintSourceColCounter - 1)
                        Else
                            ldtData.Columns(lstCurrentDataSources(lintSourceColCounter).SourceName).SetOrdinal(lintSourceGroupStartingColIndex + lintSourceColCounter)
                        End If
                        lintSourceColCounter += 1
                    End While
                    lintSourceGroupStartingColIndex += lstCurrentDataSources.Count
                End If
                'End If

                If lblnHasRegister Then
                    lintSourceGroupStartingColIndex += 1
                    lstCurrentDataSources = mstCurrentDataSources.FindAll(Function(p) (p.SourceTypeCode = SourceTypeCode.REG.ToString OrElse _
                                                                                                       p.SourceTypeCode = SourceTypeCode.RGT.ToString) AndAlso _
                                                                                                   p.ListingID = lintTraversingListingID)
                    If lstCurrentDataSources.Count > 0 Then
                        lintSourceColCounter = 0
                        While lintSourceColCounter < lstCurrentDataSources.Count
                            'lintSourceCounter += 1
                            If ldtData.Columns(lstCurrentDataSources(lintSourceColCounter).SourceName).Ordinal < lintSourceGroupStartingColIndex + lintSourceColCounter Then
                                ldtData.Columns(lstCurrentDataSources(lintSourceColCounter).SourceName).SetOrdinal(lintSourceGroupStartingColIndex + lintSourceColCounter - 1)
                            Else
                                ldtData.Columns(lstCurrentDataSources(lintSourceColCounter).SourceName).SetOrdinal(lintSourceGroupStartingColIndex + lintSourceColCounter)
                            End If
                            lintSourceColCounter += 1
                        End While
                        lintSourceGroupStartingColIndex = ldtData.Columns(mstrRegisterColPrefix + lobjListingInformation.ListingName).Ordinal + lstCurrentDataSources.Count + 1
                    End If
                End If
                If lblnHasBanklist Then
                    lintSourceGroupStartingColIndex += 1
                    lstCurrentDataSources = mstCurrentDataSources.FindAll(Function(p) (p.SourceTypeCode = SourceTypeCode.BKL.ToString OrElse _
                                                                                  p.SourceTypeCode = SourceTypeCode.PRB.ToString OrElse _
                                                                                  p.SourceTypeCode = SourceTypeCode.EPB.ToString OrElse _
                                                                                  p.SourceTypeCode = SourceTypeCode.EBL.ToString) AndAlso _
                                                                                p.ListingID = lintTraversingListingID)
                    If lstCurrentDataSources.Count > 0 Then
                        lintSourceColCounter = 0
                        While lintSourceColCounter < lstCurrentDataSources.Count
                            'lintSourceCounter += 1
                            If ldtData.Columns(lstCurrentDataSources(lintSourceColCounter).SourceName).Ordinal < lintSourceGroupStartingColIndex + lintSourceColCounter Then
                                ldtData.Columns(lstCurrentDataSources(lintSourceColCounter).SourceName).SetOrdinal(lintSourceGroupStartingColIndex + lintSourceColCounter - 1)
                            Else
                                ldtData.Columns(lstCurrentDataSources(lintSourceColCounter).SourceName).SetOrdinal(lintSourceGroupStartingColIndex + lintSourceColCounter)
                            End If
                            lintSourceColCounter += 1
                        End While
                        lintSourceGroupStartingColIndex = ldtData.Columns(mstrBanklistColPrefix + lobjListingInformation.ListingName).Ordinal + lstCurrentDataSources.Count + 1
                    End If
                End If

                'If lblnHasResearch Then
                lstCurrentDataSources = mstCurrentDataSources.FindAll(Function(p) p.SourceTypeCode = SourceTypeCode.RSH.ToString AndAlso _
                                                                            p.ListingID = lintTraversingListingID)
                If lstCurrentDataSources.Count > 0 Then
                    lintSourceColCounter = 0
                    While lintSourceColCounter < lstCurrentDataSources.Count
                        'lintSourceCounter += 1
                        If ldtData.Columns(lstCurrentDataSources(lintSourceColCounter).SourceName).Ordinal < lintSourceGroupStartingColIndex + lintSourceColCounter Then
                            ldtData.Columns(lstCurrentDataSources(lintSourceColCounter).SourceName).SetOrdinal(lintSourceGroupStartingColIndex + lintSourceColCounter - 1)
                        Else
                            ldtData.Columns(lstCurrentDataSources(lintSourceColCounter).SourceName).SetOrdinal(lintSourceGroupStartingColIndex + lintSourceColCounter)
                        End If
                        lintSourceColCounter += 1
                    End While
                    lintSourceGroupStartingColIndex += lstCurrentDataSources.Count
                End If
                'End If

                'If lblnHasPublic Then
                lstCurrentDataSources = mstCurrentDataSources.FindAll(Function(p) p.SourceTypeCode = SourceTypeCode.PBC.ToString AndAlso _
                                                                        p.ListingID = lintTraversingListingID)
                If lstCurrentDataSources.Count > 0 Then
                    lintSourceColCounter = 0
                    While lintSourceColCounter < lstCurrentDataSources.Count
                        'lintSourceCounter += 1
                        If ldtData.Columns(lstCurrentDataSources(lintSourceColCounter).SourceName).Ordinal < lintSourceGroupStartingColIndex + lintSourceColCounter Then
                            ldtData.Columns(lstCurrentDataSources(lintSourceColCounter).SourceName).SetOrdinal(lintSourceGroupStartingColIndex + lintSourceColCounter - 1)
                        Else
                            ldtData.Columns(lstCurrentDataSources(lintSourceColCounter).SourceName).SetOrdinal(lintSourceGroupStartingColIndex + lintSourceColCounter)
                        End If
                        lintSourceColCounter += 1
                    End While
                    lintSourceGroupStartingColIndex += lstCurrentDataSources.Count
                End If
                'End If
            Next

            'lintColCounter = mintTypeColIndex
            'While lintColCounter < mstPreviousProjects.Count
            '    If ldtData.Columns.Contains(mstrPreviousProjectName + " " + mstListingInformation(lintColCounter).ListingName) Then
            '        If lintColCounter = mstListingInformation.Count - 1 Then
            '            ldtData.Columns(mstrPreviousProjectName + " " + mstListingInformation(lintColCounter).ListingName).SetOrdinal(ldtData.Columns(mintTypeColIndex).Ordinal)
            '        Else
            '            ldtData.Columns(mstrPreviousProjectName + " " + mstListingInformation(lintColCounter).ListingName).SetOrdinal(ldtData.Columns(mstrSuggestedFinalListingColPrefix + " " + mstListingInformation(lintColCounter + 1).ListingName).Ordinal)
            '        End If
            '    End If
            '    lintColCounter += 1
            'End While

            'lintColCounter = 0
            'While lintColCounter < mstListingInformation.Count
            '    If ldtData.Columns.Contains(mstrPreviousProjectName + " " + mstListingInformation(lintColCounter).ListingName) Then
            '        If lintColCounter = mstListingInformation.Count - 1 Then
            '            ldtData.Columns(mstrPreviousProjectName + " " + mstListingInformation(lintColCounter).ListingName).SetOrdinal(ldtData.Columns(mintTypeColIndex).Ordinal)
            '        Else
            '            ldtData.Columns(mstrPreviousProjectName + " " + mstListingInformation(lintColCounter).ListingName).SetOrdinal(ldtData.Columns(mstrSuggestedFinalListingColPrefix + " " + mstListingInformation(lintColCounter + 1).ListingName).Ordinal)
            '        End If
            '    End If
            '    lintColCounter += 1
            'End While
            lintColCounter = 0
            While lintColCounter < ldtData.Columns.Count
                lstrColName.Remove(0, lstrColName.Length)
                lstrColName.Append(ldtData.Columns(lintColCounter).ColumnName)
                If lstExcludingCols.Contains(lstrColName.ToString) Then
                    lintColCounter += 1
                    Continue While
                End If
                'Check if the given column is data source column
                If mstAllDataSourceNameCols.Contains(lstrColName.ToString) Then
                    lobjDataSource = mstCurrentDataSources.Find(Function(p) p.SourceName = lstrColName.ToString)
                    If lobjDataSource IsNot Nothing Then
                        'Check if supports the date
                        If marrDateSuppertedSourceTypes.Contains(lobjDataSource.ESourceCode) AndAlso ldtData.Columns.Contains(lobjDataSource.SourceDate) Then
                            'If yes, then set the date column adjacent to the Source column
                            If ldtData.Columns(lobjDataSource.SourceDate).Ordinal < ldtData.Columns(lobjDataSource.SourceName).Ordinal Then
                                ldtData.Columns(lobjDataSource.SourceDate).SetOrdinal(lintColCounter)
                            Else
                                ldtData.Columns(lobjDataSource.SourceDate).SetOrdinal(lintColCounter + 1)
                            End If
                            lintColCounter = lintParentIndex + 1
                            lstExcludingCols.Add(lobjDataSource.SourceName)
                            'lstExcludingCols(lintArrColCount) = lobjDataSource.SourceName
                            'ReDim Preserve lstExcludingCols(lintArrColCount + 1)
                            lintArrColCount += 1

                            'Check if it's Research column, set the Index of it's Source column
                            If lobjDataSource.SourceTypeCode = SourceTypeCode.RSH.ToString AndAlso ldtData.Columns.Contains(lobjDataSource.SourceName + mstrSourceColSuffix) Then
                                ldtData.Columns(lobjDataSource.SourceName + mstrSourceColSuffix).SetOrdinal(ldtData.Columns(lobjDataSource.SourceName).Ordinal + 2)
                            End If
                            Continue While
                        End If
                        'Check if it's Public column, set the Filing Date and Source column
                        If lobjDataSource.SourceTypeCode = SourceTypeCode.PBC.ToString Then
                            If ldtData.Columns.Contains(lobjDataSource.PublicFilingDateCol) Then
                                If ldtData.Columns(lobjDataSource.SourceName).Ordinal > ldtData.Columns(lobjDataSource.PublicFilingDateCol).Ordinal Then
                                    ldtData.Columns(lobjDataSource.PublicFilingDateCol).SetOrdinal(ldtData.Columns(lobjDataSource.SourceName).Ordinal)
                                Else
                                    ldtData.Columns(lobjDataSource.PublicFilingDateCol).SetOrdinal(ldtData.Columns(lobjDataSource.SourceName).Ordinal + 1)
                                End If
                                If ldtData.Columns(lobjDataSource.SourceName).Ordinal > ldtData.Columns(lobjDataSource.PublicSourceCol).Ordinal Then
                                    ldtData.Columns(lobjDataSource.PublicSourceCol).SetOrdinal(ldtData.Columns(lobjDataSource.SourceName).Ordinal + 1)
                                Else
                                    ldtData.Columns(lobjDataSource.PublicSourceCol).SetOrdinal(ldtData.Columns(lobjDataSource.SourceName).Ordinal + 2)
                                End If
                            End If
                            If grdData.DataSource IsNot Nothing Then
                                If grdData.Rows.Band.Columns.Exists(lobjDataSource.PublicFilingDateCol) Then
                                    grdData.Rows.Band.Columns(lobjDataSource.PublicFilingDateCol).Header.VisiblePosition = grdData.Rows.Band.Columns(lobjDataSource.SourceName).Header.VisiblePosition + 1
                                    grdData.Rows.Band.Columns(lobjDataSource.PublicSourceCol).Header.VisiblePosition = grdData.Rows.Band.Columns(lobjDataSource.SourceName).Header.VisiblePosition + 2
                                End If
                            End If
                        End If
                    End If
                End If
                lintColCounter += 1
            End While
            lstrColName = Nothing
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            lstrColName = Nothing
            lobjDataSource = Nothing
            lstExcludingCols = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' To set the values of DataSource Group Column values
    ''' </summary>
    ''' <param name="ldtData"></param>
    ''' <remarks></remarks>
    Private Sub SetParentGroupValues(ByVal ldtData As DataTable, ByVal pblnCanRecalculate As Boolean)
        Dim lblnCanSetCurrentListingValue As Boolean = True
        Dim lobjListingInformation As ListingInformation = Nothing
        Dim sqlBulkCopy As System.Data.SqlClient.SqlBulkCopy = Nothing
        Try
            'CanLoadPositionFromDB
            lobjListingInformation = mstListingInformation.Find(Function(p) p.CanLoadPositionFromDB = True)
            If lobjListingInformation Is Nothing Then
                lblnCanSetCurrentListingValue = False
            End If
            For Each lrow As DataRow In ldtData.Rows
                For Each lstListingInformation As ListingInformation In mstListingInformation
                    If lblnCanSetCurrentListingValue AndAlso ((pblnCanRecalculate AndAlso mintPreviousProjectID = 0) OrElse (mintPreviousProjectID > 0)) Then
                        If lstListingInformation.CanLoadPositionFromDB Then
                            lrow.Item(lstListingInformation.CurrentListingName) = ""
                        End If
                    End If
                    If pblnCanRecalculate Then
                        lrow.Item(mstrSuggestedFinalListingColPrefix + lstListingInformation.ListingName) = ""
                    End If
                Next
            Next
            If pblnCanRecalculate Then
                ' ''Clear the Staging Sort table for the current UserID and ProjectID
                CommonManager.ClearDHSortBulkStagingTable("STG_AutofillSuggestion", 0, mintProjectID)
                sqlBulkCopy = New System.Data.SqlClient.SqlBulkCopy(mstrConnectionstring)
                'Define column mappings to specify the columnn/data to be saved in staging table
                sqlBulkCopy.DestinationTableName = "STG_AutofillSuggestion"
                sqlBulkCopy.ColumnMappings.Add("InvestorID", "InvestorID")
                sqlBulkCopy.ColumnMappings.Add("LinkID", "LinkID")
                sqlBulkCopy.ColumnMappings.Add("FundID", "FundID")
                sqlBulkCopy.ColumnMappings.Add("ProjectID", "ProjectID")

                sqlBulkCopy.WriteToServer(ldtData)
                sqlBulkCopy.Close()
                mclsDataHubManager.GetCalculatedSuggestions(mintClientID, mintProjectID, mintPreviousProjectID, "", ldtData, -1, -1, -1, "", lblnCanSetCurrentListingValue)
                ldtData.AcceptChanges()
            End If

            ''''''''''Starts: Sukhminder Singh - 24th Sep 2012 - Autofill part is commented, because it has various levels which require more effort to implement, will be done in Phase 2
            'If mintPreviousProjectID <> 0 AndAlso lblnCanSetCurrentListingValue Then
            '    mclsDataHubManager.GetCurrentListingValue(mintProjectID, "", ldtData, -1, -1, -1, "")
            'End If
            ''''''''''Ends: Sukhminder Singh - 24th Sep 2012 - Autofill part is commented, because it has various levels which require more effort to implement, will be done in Phase 2
            ldtData.AcceptChanges()

            'To get the missing data columns e.g. Research supporting columns
            GetMissingDataColumns(ldtData)

            'To get the listing's associated data
            ConductRetrieveCurrentListingData()
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            lobjListingInformation = Nothing
            sqlBulkCopy = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' To get the missing data columns e.g. Research supporting columns
    ''' </summary>
    ''' <param name="ldtData"></param>
    ''' <remarks></remarks>
    Private Sub GetMissingDataColumns(ByRef ldtData As DataTable)
        Dim ldtUpdatedData As DataTable = Nothing
        Dim lstNonPivotCols As New List(Of String)
        Dim lstPivotCols As New List(Of String)
        Dim lstrResearchEntities As StringBuilder = Nothing
        Dim lstResearchMissingDataSources As List(Of CurrentDataSources) = Nothing
        Dim lobjResearchDataSources As CurrentDataSources = Nothing
        Dim lstrTraversingSourceName As String = ""
        Dim lstResearchSources As List(Of CurrentDataSources) = Nothing
        Try
            lstrResearchEntities = New StringBuilder
            lstResearchMissingDataSources = New List(Of CurrentDataSources)
            lstResearchSources = mstCurrentDataSources.FindAll(Function(p) p.SourceTypeCode = SourceTypeCode.RSH.ToString)
            ''If research's supporting column are missing, then get those
            For Each lobjResearchDataSources In lstResearchSources
                If ldtData.Columns.Contains(lobjResearchDataSources.SourceName + mstrClientSpecificSourceColSuffix) = False Then
                    mstSysColumns.Add(lobjResearchDataSources.SourceName + mstrClientSpecificSourceColSuffix)
                    mstSysColumns.Add(lobjResearchDataSources.SourceName + mstrGenericSourceColSuffix)
                    lstrResearchEntities.Append(lobjResearchDataSources.EntityID)
                    lstrResearchEntities.Append(",")
                    lstResearchMissingDataSources.Add(lobjResearchDataSources)
                End If
            Next
            If lstrResearchEntities.Length = 0 Then
                Exit Sub
            Else
                lstrResearchEntities.Length = lstrResearchEntities.Length - 1
            End If
            lstNonPivotCols.Add("InvestorID")
            lstNonPivotCols.Add("FundID")
            lstPivotCols.Add("Position")
            lstPivotCols.Add(mstrFormulaColSuffix.Trim)
            lstPivotCols.Add(mstrSOFColPrefix)
            lstPivotCols.Add(mstrSourceDateColSuffix.Trim)
            lstPivotCols.Add(mstrFilingDateColSuffix.Trim)
            lstPivotCols.Add(mstrSourceColSuffix.Trim)
            lstPivotCols.Add(mstrClientSpecificSourceColSuffix.Trim)
            lstPivotCols.Add(mstrGenericSourceColSuffix.Trim)
            lstPivotCols.Add("RSource")

            ldtUpdatedData = mclsDataHubManager.GetLockedUpdatedData(mintProjectID, lstrResearchEntities.ToString, lstNonPivotCols, lstPivotCols, mstrPreviousProjectName, _
                                                                   lstResearchMissingDataSources, 0, Nothing)
            SetPrimaryKey(ldtUpdatedData)
            RemoveUnnecessaryAssociatedFields(ldtUpdatedData, lstResearchMissingDataSources)
            Dim lintColCounter As Integer
            Dim lstrTraversingColName As String
            lintColCounter = ldtUpdatedData.Columns.Count - 1
            While lintColCounter >= 0
                lstrTraversingColName = ldtUpdatedData.Columns(lintColCounter).ColumnName
                'lstrTraversingColName = mdtDEAssociatedData.Columns(lintColCounter).ColumnName
                If lstrTraversingColName.Equals("InvestorID") OrElse lstrTraversingColName.Equals("FundID") Then
                    lintColCounter -= 1
                    Continue While
                End If
                If lstrTraversingColName.StartsWith(mstrSOFColPrefix) OrElse lstrTraversingColName.EndsWith(mstrFormulaColSuffix) Then
                    ldtUpdatedData.Columns.Remove(lstrTraversingColName)
                End If
                lintColCounter -= 1
            End While
            ldtUpdatedData.AcceptChanges()
            ldtData.Merge(ldtUpdatedData, True, MissingSchemaAction.Add)
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            ldtUpdatedData = Nothing
            lstNonPivotCols = Nothing
            lstPivotCols = Nothing
            lstrResearchEntities = Nothing
            lstResearchMissingDataSources = Nothing
            lstResearchSources = Nothing
            lobjResearchDataSources = Nothing
        End Try
    End Sub

#End Region

#Region "Listing Related"

    ''' <summary>
    ''' Conduct retrieval of previous listing data
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ConductRetrievePreviousListingData()
        'Cancel out the cut operation
        CancelOutCutOperation()
        Dim lobjData As PreviousProjects = Nothing
        Dim lstrColName As String
        Dim lstNonPivotCols As New List(Of String)
        Dim lstPivotCols As New List(Of String)
        Dim ldtUpdatedPreviousData As DataTable
        Dim ldtCurrentData As DataTable = Nothing
        Dim lstRetrievingListings As New List(Of PreviousProjects)
        Dim lintColCounter As Integer
        Dim lstrTraversingColName As String
        Try
            'Traverse each selected column and retrieve the previous position data
            For Each lCol As ColumnHeader In grdData.Selected.Columns
                lstrColName = lCol.Caption
                lobjData = mstPreviousProjects.Find(Function(p) p.DeliveryListing = lstrColName)
                If lobjData IsNot Nothing Then
                    lstRetrievingListings.Add(lobjData)
                End If
            Next
            If lstRetrievingListings.Count > 0 Then
                'If there are, get the latest data from database
                lstNonPivotCols.Add("InvestorID")
                lstNonPivotCols.Add("FundID")
                lstPivotCols.Add("Position")
                lstPivotCols.Add(mstrFormulaColSuffix.Trim)
                lstPivotCols.Add(mstrSOFColPrefix)
                ldtCurrentData = grdData.DataSource
                mclsDataHubManager.UpdateAndGetProjectDatabase(ldtCurrentData, mintProjectID)
                mblnAnyChangesInLastProject = True
                ldtUpdatedPreviousData = mclsDataHubManager.GetPreviousListingData(mintProjectID, String.Join(",", lstRetrievingListings.Select(Function(lobjListing) lobjListing.ListingID)).ToString, lstNonPivotCols, lstPivotCols, mstrPreviousProjectName)
                For Each lCol As DataColumn In ldtUpdatedPreviousData.Columns
                    If lCol.ColumnName.Equals("InvestorID") OrElse lCol.ColumnName.Equals("FundID") Then Continue For
                    lstrColName = lCol.Caption
                    For Each lobjPreviousListing As PreviousProjects In lstRetrievingListings
                        If lstrColName.Contains(lobjPreviousListing.ListingID.ToString) Then
                            lCol.ColumnName = lstrColName.Replace(lobjPreviousListing.ListingID.ToString, lobjData.DeliveryListing)
                            'grdData.DisplayLayout.Bands(0).Columns(lCol.ColumnName).CellActivation = Activation.AllowEdit
                        End If
                    Next
                Next
                SetPrimaryKey(ldtUpdatedPreviousData)
                mdtFLAssociatedData = New DataTable
                mdtFLAssociatedData = ldtUpdatedPreviousData.Copy
                Dim columnNames = mdtFLAssociatedData.Columns.Cast(Of DataColumn)() _
                              .Select(Function(column) column.ColumnName).ToArray()
                lintColCounter = columnNames.Length - 1
                While lintColCounter >= 0
                    lstrTraversingColName = columnNames(lintColCounter)
                    'lstrTraversingColName = mdtFLAssociatedData.Columns(lintColCounter).ColumnName
                    If lstrTraversingColName.Equals("InvestorID") OrElse lstrTraversingColName.Equals("FundID") Then
                        lintColCounter -= 1
                        Continue While
                    End If
                    If marrPreviousProjects.Contains(lstrTraversingColName) Then
                        mdtFLAssociatedData.Columns.Remove(lstrTraversingColName)
                    Else
                        ldtUpdatedPreviousData.Columns.Remove(lstrTraversingColName)
                    End If
                    lintColCounter -= 1
                End While

                SetPrimaryKey(mdtFLAssociatedData)
                mdtFLAssociatedData.AcceptChanges()
                ldtUpdatedPreviousData.AcceptChanges()
                ldtCurrentData = grdData.DataSource
                ldtCurrentData.Merge(ldtUpdatedPreviousData, False, MissingSchemaAction.Add)
                ldtCurrentData.AcceptChanges()
                For Each lCol As DataColumn In ldtUpdatedPreviousData.Columns
                    If lCol.ColumnName.Equals("InvestorID") OrElse lCol.ColumnName.Equals("FundID") Then Continue For
                    If lCol.ColumnName.StartsWith(mstrSOFColPrefix) OrElse lCol.ColumnName.EndsWith(mstrFormulaColSuffix) Then
                        grdData.DisplayLayout.Bands(0).Columns(lCol.ColumnName).Hidden = True
                    End If
                    grdData.DisplayLayout.Bands(0).Columns(lCol.ColumnName).CellActivation = Activation.AllowEdit
                    grdData.Rows.Band.Columns(lCol.ColumnName).CellAppearance.BackColor = grdData.DisplayLayout.Appearances("VisiblePosition").BackColor
                Next
            End If
            'Unselect all the selected columns
            grdData.Selected.Columns.Clear()
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            ldtCurrentData = Nothing
            lobjData = Nothing
            lstNonPivotCols = Nothing
            lstPivotCols = Nothing
            ldtUpdatedPreviousData = Nothing
            lstRetrievingListings = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' Conduct retrieval of currnt listing data
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ConductRetrieveCurrentListingData()
        Dim lobjData As ListingInformation = Nothing
        Dim lstrColName As String
        Dim lstNonPivotCols As New List(Of String)
        Dim lstPivotCols As New List(Of String)
        Dim ldtCurrentListingSOFFormulaData As DataTable
        Dim ldtCurrentData As DataTable = Nothing
        Dim lintColCounter As Integer
        Dim lstrTraversingColName As String
        Dim lstrAllListingIDs As String
        Try
            lstNonPivotCols.Add("InvestorID")
            lstNonPivotCols.Add("FundID")
            lstPivotCols.Add("Position")
            lstPivotCols.Add(mstrFormulaColSuffix.Trim)
            lstPivotCols.Add(mstrSOFColPrefix)
            lstrAllListingIDs = String.Join(",", mstListingInformation.Select(Function(lobjListing) lobjListing.ListingID)).ToString
            If mstPreviousProjects.Count > 0 Then
                lstrAllListingIDs += ","
            End If
            'lstrAllListingIDs += String.Join(",", mstPreviousProjects.Select(Function(lobjListing) lobjListing.ListingID)).ToString
            ldtCurrentListingSOFFormulaData = mclsDataHubManager.GetPreviousListingData(mintProjectID, lstrAllListingIDs, lstNonPivotCols, lstPivotCols, mstrPreviousProjectName)
            lintColCounter = 0
            Dim lCol As DataColumn = Nothing
            While lintColCounter < ldtCurrentListingSOFFormulaData.Columns.Count
                lCol = ldtCurrentListingSOFFormulaData.Columns(lintColCounter)
                If lCol.ColumnName.Equals("InvestorID") OrElse lCol.ColumnName.Equals("FundID") Then
                    lintColCounter += 1
                    Continue While
                End If
                lstrColName = lCol.Caption
                For Each lobjListingInformation As ListingInformation In mstListingInformation
                    If lstrColName.Contains(lobjListingInformation.ListingID.ToString) Then
                        lCol.ColumnName = lstrColName.Replace(lobjListingInformation.ListingID.ToString, lobjListingInformation.CurrentListingName)
                        lintColCounter += 1
                        Continue While
                    End If
                Next
                For Each lobjPreviousProjects As PreviousProjects In mstPreviousProjects
                    If lstrColName.Contains(lobjPreviousProjects.ListingID.ToString) Then
                        lCol.ColumnName = lstrColName.Replace(lobjPreviousProjects.ListingID.ToString, lobjPreviousProjects.DeliveryListing)
                        lintColCounter += 1
                        Continue While
                    End If
                Next
                lintColCounter += 1
            End While
            SetPrimaryKey(ldtCurrentListingSOFFormulaData)
            mdtFLAssociatedData = New DataTable
            mdtFLAssociatedData = ldtCurrentListingSOFFormulaData.Copy
            Dim columnNames = mdtFLAssociatedData.Columns.Cast(Of DataColumn)() _
                          .Select(Function(column) column.ColumnName).ToArray()
            lintColCounter = columnNames.Length - 1
            While lintColCounter >= 0
                lstrTraversingColName = columnNames(lintColCounter)
                'lstrTraversingColName = mdtFLAssociatedData.Columns(lintColCounter).ColumnName
                If lstrTraversingColName.Equals("InvestorID") OrElse lstrTraversingColName.Equals("FundID") Then
                    lintColCounter -= 1
                    Continue While
                End If
                If mstListingInformation.Find(Function(p) p.CurrentListingName = lstrTraversingColName) IsNot Nothing OrElse mstPreviousProjects.Find(Function(p) p.DeliveryListing = lstrTraversingColName) IsNot Nothing Then
                    mdtFLAssociatedData.Columns.Remove(lstrTraversingColName)
                End If
                lintColCounter -= 1
            End While

            SetPrimaryKey(mdtFLAssociatedData)
            mdtFLAssociatedData.AcceptChanges()
            'Unselect all the selected columns
            grdData.Selected.Columns.Clear()
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            ldtCurrentData = Nothing
            lobjData = Nothing
            lstNonPivotCols = Nothing
            lstPivotCols = Nothing
            ldtCurrentListingSOFFormulaData = Nothing
        End Try
    End Sub

#End Region

#Region "Miscellaneous"

    ''' <summary>
    ''' To reset Formula and SOF of the active row if user directly removes the content of the cell without going into Edit mode
    ''' </summary>
    ''' <param name="lstrDataSourceColName"></param>
    ''' <remarks></remarks>
    Private Sub ResetFormulaAndSOF(ByVal lstrDataSourceColName As String)
        If grdData.ActiveCell Is Nothing Then Exit Sub
        'Cancel out the cut operations
        CancelOutCutOperation()
        Dim lblnIsSumOfFunds As Boolean = False
        Dim lintInvestorPositions As Int64
        'If user directly press delete on a cell on removes the content, then reset it's formula to blank, if it exists
        If HasFormulas(GetFormula(grdData.ActiveRow.GetCellValue("InvestorID"), grdData.ActiveRow.GetCellValue("FundID"), grdData.ActiveRow.GetCellValue("LinkID"), lstrDataSourceColName, True)) Then
            If grdData.ActiveRow.GetCellValue(lstrDataSourceColName).ToString.Equals("") Then
                SetAssociatedFormula(grdData.ActiveRow.GetCellValue("InvestorID"), grdData.ActiveRow.GetCellValue("FundID"), lstrDataSourceColName, "")
                'grdData.ActiveRow.Cells(lstrDataSourceColName + mstrFormulaColSuffix).Value = ""
            End If
        End If
        'If user directly press delete on a cell or removes the content, then reset it's SOF to blank
        If grdData.ActiveRow.GetCellValue(lstrDataSourceColName).ToString.Equals("") AndAlso grdData.ActiveRow.GetCellValue("LinkID") = 0 Then
            'lblnIsSumOfFunds = CheckSumOfFunds(grdData.ActiveRow.Index, lstrDataSourceColName)
            lblnIsSumOfFunds = CheckSumOfFunds(grdData.ActiveRow.GetCellValue("InvestorID"), lstrDataSourceColName, True, True)
            If lblnIsSumOfFunds Then
                lintInvestorPositions = CalculateSumOfFundPositions(grdData.ActiveRow.Index, lstrDataSourceColName, False)
                If lintInvestorPositions > 0 Then
                    SetAssociatedIsSumOfFunds(grdData.ActiveRow.GetCellValue("InvestorID"), grdData.ActiveRow.GetCellValue("FundID"), lstrDataSourceColName, False)
                    'grdData.ActiveRow.Cells(mstrSOFColPrefix + lstrDataSourceColName).Value = False
                End If
            End If
        End If
    End Sub

    ''' <summary>
    ''' To get the type of fixed state source
    ''' </summary>
    ''' <param name="lstrColHeader"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function GetFixedStateType(ByVal lstrColHeader As String) As FixedStateColumnType
        Dim lenmFixedStateColumnType As FixedStateColumnType
        If mstPublicFilingDateCols.Contains(lstrColHeader) Then
            lenmFixedStateColumnType = FixedStateColumnType.PublicFilingDate
        ElseIf mstPublicSourcesCols.Contains(lstrColHeader) Then
            lenmFixedStateColumnType = FixedStateColumnType.PublicSource
        ElseIf mstResearchSourceCols.Contains(lstrColHeader) Then
            lenmFixedStateColumnType = FixedStateColumnType.ResearchSource
        ElseIf mstAllDataSourceDateCols.Contains(lstrColHeader) Then
            lenmFixedStateColumnType = FixedStateColumnType.SourceDate
        ElseIf mstAllDataSourceNameCols.Contains(lstrColHeader) Then
            lenmFixedStateColumnType = FixedStateColumnType.SourceName
        End If
        Return lenmFixedStateColumnType
    End Function

    ''' <summary>
    ''' To set the column's fixed state status
    ''' </summary>
    ''' <param name="pstrSourceName"></param>
    ''' <param name="pstrSourceDate"></param>
    ''' <remarks></remarks>
    Private Sub SetColumnFixedState(ByVal pobjCurrentDataSources As CurrentDataSources, ByVal penmFixedStateColumnType As FixedStateColumnType)
        Dim lblnSourceDateFixedStatus As Boolean
        Dim lblnPublicFilingDateFixedStatus As Boolean
        Dim lblnPublicSourceFixedStatus As Boolean
        Dim lblnResearchSourceFixedStatus As Boolean
        Dim lblnSourceNameFixedStatus As Boolean
        Dim rootBand As UltraGridBand = grdData.Rows.Band
        If pobjCurrentDataSources Is Nothing Then Exit Sub
        If penmFixedStateColumnType = FixedStateColumnType.SourceName Then
            lblnSourceNameFixedStatus = rootBand.Columns(pobjCurrentDataSources.SourceName).Header.Fixed
            If pobjCurrentDataSources.SourceDate.Equals("") = False AndAlso rootBand.Columns.Exists(pobjCurrentDataSources.SourceDate) Then
                rootBand.Columns(pobjCurrentDataSources.SourceDate).Header.Fixed = lblnSourceNameFixedStatus
            End If
            If pobjCurrentDataSources.PublicFilingDateCol.Equals("") = False Then
                rootBand.Columns(pobjCurrentDataSources.PublicFilingDateCol).Header.Fixed = lblnSourceNameFixedStatus
                rootBand.Columns(pobjCurrentDataSources.PublicSourceCol).Header.Fixed = lblnSourceNameFixedStatus
            End If
            If pobjCurrentDataSources.ResearchSourceCol.Equals("") = False AndAlso rootBand.Columns.Exists(pobjCurrentDataSources.SourceDate) Then
                rootBand.Columns(pobjCurrentDataSources.ResearchSourceCol).Header.Fixed = lblnSourceNameFixedStatus
            End If
        ElseIf penmFixedStateColumnType = FixedStateColumnType.SourceDate Then
            lblnSourceDateFixedStatus = rootBand.Columns(pobjCurrentDataSources.SourceDate).Header.Fixed
            rootBand.Columns(pobjCurrentDataSources.SourceName).Header.Fixed = lblnSourceDateFixedStatus
            If pobjCurrentDataSources.ResearchSourceCol.Equals("") = False Then
                rootBand.Columns(pobjCurrentDataSources.ResearchSourceCol).Header.Fixed = lblnSourceDateFixedStatus
            End If
        ElseIf penmFixedStateColumnType = FixedStateColumnType.PublicFilingDate Then
            lblnPublicFilingDateFixedStatus = rootBand.Columns(pobjCurrentDataSources.PublicFilingDateCol).Header.Fixed
            rootBand.Columns(pobjCurrentDataSources.SourceName).Header.Fixed = lblnPublicFilingDateFixedStatus
            rootBand.Columns(pobjCurrentDataSources.PublicSourceCol).Header.Fixed = lblnPublicFilingDateFixedStatus
        ElseIf penmFixedStateColumnType = FixedStateColumnType.PublicSource Then
            lblnPublicSourceFixedStatus = rootBand.Columns(pobjCurrentDataSources.PublicSourceCol).Header.Fixed
            rootBand.Columns(pobjCurrentDataSources.SourceName).Header.Fixed = lblnPublicSourceFixedStatus
            rootBand.Columns(pobjCurrentDataSources.PublicSourceCol).Header.Fixed = lblnPublicSourceFixedStatus
        ElseIf penmFixedStateColumnType = FixedStateColumnType.ResearchSource Then
            lblnResearchSourceFixedStatus = rootBand.Columns(pobjCurrentDataSources.ResearchSourceCol).Header.Fixed
            rootBand.Columns(pobjCurrentDataSources.SourceName).Header.Fixed = lblnResearchSourceFixedStatus
            rootBand.Columns(pobjCurrentDataSources.SourceDate).Header.Fixed = lblnResearchSourceFixedStatus
        End If
    End Sub

    ''' <summary>
    ''' To mark the column header in different color if any doubt exists for that data source
    ''' </summary>
    ''' <param name="pstrEntityIDs">EntityID of Data Sources</param>
    ''' <remarks></remarks>
    Private Sub GetEntityDoubtStatus(ByVal pstrEntityIDs As String)
        Dim lstEntityDoubtStatus As IList(Of EntityDoubtStatus) = Nothing
        Try
            'Get the doubt status of the given data sources
            lstEntityDoubtStatus = mclsDataHubManager.GetEntityDoubtStatus(mintProjectID, pstrEntityIDs)
            For Each lRow As EntityDoubtStatus In lstEntityDoubtStatus
                'Mark with RED if any doubt exists
                If lRow.HasDoubt = True Then
                    grdData.Rows.Band.Columns(lRow.SourceName).Header.Appearance.BackColor = grdData.DisplayLayout.Appearances("RedBackColor").BackColor
                Else
                    'Otherwise given the normal color
                    grdData.Rows.Band.Columns(lRow.SourceName).Header.Appearance.BackColor = grdData.DisplayLayout.Appearances("ColHeadBackColor").BackColor 'mclrColHeadBackColor
                End If
            Next
            lstEntityDoubtStatus = Nothing
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            lstEntityDoubtStatus = Nothing
        End Try
        ''Get the doubt status of the given data sources
    End Sub

    ''' <summary>
    ''' To delete the data sources from the grid
    ''' </summary>
    ''' <param name="lstrDataEntityNames"></param>
    ''' <remarks></remarks>
    Private Sub DeleteDataEntityFromFrontEnd(ByVal lstrDataEntityNames As String, ByRef ldtData As DataTable)
        Dim larrDeletedCol() As String
        Dim lobjDataSource As CurrentDataSources
        Dim lstrDeletingCol As String
        Try
            larrDeletedCol = lstrDataEntityNames.Split(",")
            'Traverse the data sources list and remove them and their associated columns
            For Each lCol As String In larrDeletedCol
                If lCol.Equals("") = False Then
                    lstrDeletingCol = lCol
                    lobjDataSource = mstCurrentDataSources.Find(Function(p) p.SourceName = lstrDeletingCol)
                    SetPreviousProjectDataSourcesVisibility(lobjDataSource, False, 0)
                    mstCurrentDataSources.Remove(lobjDataSource)
                    mstEditableDataSourceNameCols.Remove(lobjDataSource.SourceName)
                    mstAllDataSourceNameCols.Remove(lobjDataSource.SourceName)
                    mstAllDataSourceDateCols.Remove(lobjDataSource.SourceDate)
                    ldtData.Columns.Remove(lCol)
                    If grdData.Rows.Band.Columns.Exists(lCol + mstrSourceDateColSuffix) Then
                        ldtData.Columns.Remove(lCol + mstrSourceDateColSuffix)
                    End If
                    If grdData.Rows.Band.Columns.Exists(lCol + mstrFilingDateColSuffix) Then
                        ldtData.Columns.Remove(lCol + mstrFilingDateColSuffix)
                    End If
                    If grdData.Rows.Band.Columns.Exists(lCol + mstrSourceColSuffix) Then
                        ldtData.Columns.Remove(lCol + mstrSourceColSuffix)
                    End If
                    If grdData.Rows.Band.Columns.Exists(lCol + mstrClientSpecificSourceColSuffix) Then
                        ldtData.Columns.Remove(lCol + mstrClientSpecificSourceColSuffix)
                    End If
                    If grdData.Rows.Band.Columns.Exists(lCol + mstrGenericSourceColSuffix) Then
                        ldtData.Columns.Remove(lCol + mstrGenericSourceColSuffix)
                    End If
                End If
            Next
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            lobjDataSource = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' Hide the columns not exist in the array marrPreviousDataSourceNameCols. and display which are present in the array.
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub DataColumnsHidden(ByVal blnDE As Boolean)
        For Each lcol As UltraGridColumn In grdData.DisplayLayout.Bands(0).Columns
            If Not marrPreviousDataSourceNameCols.Contains(lcol.Header.Caption) And Not marrPreviousSourceDateCols.Contains(lcol.Header.Caption) Then
                If blnDE Then
                    If marrAllVisibleSourceNameCols.Contains(lcol.Header.Caption) Then
                        lcol.Hidden = False
                    Else
                        lcol.Hidden = True
                    End If
                Else
                    If marrVisibleColumnsFL.Contains(lcol.Header.Caption) Then
                        lcol.Hidden = False
                    Else
                        lcol.Hidden = True
                    End If
                End If
            End If
        Next
    End Sub

    ''' <summary>
    ''' Check if column name exist in grid using mdtAppendCurrentDataSource (newly or updated and all the columns are added).
    ''' If exist update the columns added.
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub SetDataSourceColumnListReturn()
        Dim lobjChangedSource As CurrentDataSources
        Dim dSource As DataTable
        Try
            If mdtAppendCurrentDataSource IsNot Nothing Then
                If mdtAppendCurrentDataSource.Rows.Count > 0 Then
                    For Each row As DataRow In mdtAppendCurrentDataSource.Rows
                        'Row in mdtAppendCurrentDataSource is the column of Grid.
                        'If grdData.DisplayLayout.Bands(0).Columns.Exists(row(0).ToString) Then
                        'Find the column in grid.
                        lobjChangedSource = mstCurrentDataSources.Find(Function(p) p.EntityID = row("EntityID").ToString)
                        'If the row exist in mdtCurrentDataSources update the row.
                        If lobjChangedSource IsNot Nothing Then
                            lobjChangedSource.IsND = row("IsND").ToString
                            lobjChangedSource.IsNIL = row("IsNIL").ToString
                        End If
                        If lobjChangedSource.IsND = False And lobjChangedSource.IsNIL = False Then
                            If grdData.DisplayLayout.Bands(0).Columns.Exists(lobjChangedSource.SourceName) Then
                                grdData.DisplayLayout.Bands(0).Columns(lobjChangedSource.SourceName).Header.Appearance.BackColor = _
                                grdData.DisplayLayout.Bands(0).Columns("Name").Header.Appearance.BackColor
                            End If
                        Else
                            If grdData.DisplayLayout.Bands(0).Columns.Exists(lobjChangedSource.SourceName) Then
                                grdData.DisplayLayout.Bands(0).Columns(lobjChangedSource.SourceName).Header.Appearance.BackColor = Color.Red
                            End If
                        End If
                        'dSource = CType(grdData.DataSource, DataTable)

                        'Also update the column name of the grid.
                        'dSource.Columns(row("OldSourceName").ToString).ColumnName = row("SourceName").ToString
                        'End If
                    Next
                End If
            End If
        Catch ex As Exception
            Me.FormulateAndLogError(ex, "ColumnList", mintProjectID)
        Finally
            lobjChangedSource = Nothing
            dSource = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' Set the default text for Notes text box
    ''' </summary>
    ''' <param name="txtNotes"></param>
    ''' <remarks></remarks>
    Private Sub SetDENotesText(ByVal txtNotes As TextBox)
        Dim lstrLockedBy As New StringBuilder
        Dim lblnCanInsertNewLine As Boolean
        If txtNotes Is txtDENotes Then
            For Each lobjCurrentDataSources As CurrentDataSources In mstCurrentDataSources
                If lobjCurrentDataSources.AccessStatus = SourceAccessbility.Locked.ToString Then
                    If lobjCurrentDataSources.SourceTypeCode = SourceTypeCode.UPD.ToString Then
                        lstrLockedBy.Append(lobjCurrentDataSources.SourceName.Substring(0, lobjCurrentDataSources.SourceName.Length - lobjCurrentDataSources.ListingName.Length).Trim)
                        Exit For
                    Else
                        lstrLockedBy.Append(lobjCurrentDataSources.SourceName)
                    End If
                End If
            Next
            If lstrLockedBy.Length > 0 Then
                lstrLockedBy.Append(" - ")
            End If
        Else
            lstrLockedBy.Append("")
        End If

        If txtNotes.Text.Length > CommonCLL.UserFullName.Length Then
            If CommonCLL.Reverse(CommonCLL.Reverse(txtNotes.Text.Trim).Substring(2, CommonCLL.UserFullName.Length - 1)) <> CommonCLL.UserFullName.Trim Then
                If System.Text.Encoding.ASCII.GetBytes(txtNotes.Text(txtNotes.Text.Length - 1))(0) <> 10 Then
                    txtNotes.Text += Environment.NewLine
                End If
                txtNotes.Text += "- " + lstrLockedBy.ToString + CommonCLL.UserFullName + ": "
            End If
        Else
            lblnCanInsertNewLine = False
            If txtNotes.Text.Length = 0 Then
                lblnCanInsertNewLine = True
            Else
                If System.Text.Encoding.ASCII.GetBytes(txtNotes.Text(txtNotes.Text.Length - 1))(0) <> 10 Then
                    lblnCanInsertNewLine = True
                End If
            End If
            If lblnCanInsertNewLine Then
                txtNotes.Text += Environment.NewLine
            End If
            txtNotes.Text += "- " + lstrLockedBy.ToString + CommonCLL.UserFullName + ": "
        End If
        txtNotes.Select(txtNotes.Text.Length, 0)
        lstrLockedBy = Nothing
    End Sub

    ''' <summary>
    ''' Set the tooltip to the control.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="message"></param>
    ''' <remarks></remarks>
    Private Sub ShowToolTip(ByVal sender As Object, ByVal message As String)
        Dim tipInfo As UltraToolTipInfo
        Try
            If grdData.DataSource Is Nothing Then Exit Sub
            tipInfo = New UltraToolTipInfo(message, +ToolTipImage.None, String.Empty, DefaultableBoolean.False)
            tipInfo.Appearance.BackColor = grdData.DisplayLayout.Appearances("ToolTipInfo").BackColor '. Color.FromArgb(246, 214, 115)
            UltraToolTipManager1.Enabled = True
            UltraToolTipManager1.SetUltraToolTip(sender, tipInfo)
            UltraToolTipManager1.ShowToolTip(sender)
        Catch ex As Exception
            Me.FormulateAndLogError(ex, mstrScreenName, mintProjectID)
        Finally
            tipInfo = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' To show the right click context menu
    ''' </summary>
    ''' <param name="mousePoint"></param>
    ''' <remarks></remarks>
    Private Sub ShowContextMenu(ByVal mousePoint As Point)
        Dim lobjData As CurrentDataSources = Nothing
        Dim lobjPreviousData As PreviousDataSources = Nothing
        Dim el As UIElement = grdData.DisplayLayout.UIElement.ElementFromPoint(mousePoint)
        Dim cell As UltraGridCell = CommonCLL.GetCell(el)
        Dim row As UltraGridRow = CommonCLL.GetRow(el)
        Dim lcolSelectedColumn As UltraGridColumn = CommonCLL.GetColumn(el)

        Dim lblnIsFirstSelectedRow As Boolean
        Dim lintGetFirstLinkID As Integer
        Dim lblnCanAccessDelete As Boolean
        Dim lintColCounter As Integer = 0
        Dim lblnIsSOFExists As Boolean
        Dim lblnIsFormulaExists As Boolean
        Dim lblnIsManual As Boolean
        Dim lintLastIndexToCheck As Integer

        Dim lblnIsLockMenu As Boolean
        Dim lblnCanShowLock As Boolean
        Dim lblnCanShowUnLock As Boolean
        Dim lblnCanHideVisible As Boolean
        Dim lblnCanLoadMappingVisible As Boolean
        Dim lblnCanAddNewVisible As Boolean
        Dim lblnIsLockedSourceName As Boolean
        Dim lblnIsLockedSourceDate As Boolean
        Dim lblnCanShowDeleteColumn As Boolean
        Dim lblnCanShowRetrieve As Boolean
        Dim lblnCanShowCarryForward As Boolean
        Dim lstrDataEntityColName As String = ""

        Dim lstrColName As String
        Dim lobjCurrentDataSources As CurrentDataSources = Nothing

        Dim lstrColumnName As String
        Dim lobjPreviousProjects As PreviousProjects = Nothing
        Dim lobjPreviousDataSources As PreviousDataSources = Nothing
        Dim lintPreviousProjectCounter As Int16 = 0
        Try
            If lcolSelectedColumn Is Nothing Then
                mstrRightClickColName = ""
            End If
            If cell IsNot Nothing Then
                If cell.Column.Header.Caption = "Name" Then
                    ControlVisibilityRowContextMenu()
                    cRowMenu.Show(grdData, mousePoint)
                End If
                If cell.Row.GetCellValue("IsManaged") = True Then
                    cRowMenu.Items("mnuAddNewInvestor").Enabled = False
                    cRowMenu.Items("mnuAddNewFund").Enabled = False
                    cRowMenu.Items("mnuChangedFund").Enabled = False
                    cRowMenu.Items("mnuRowEdit").Enabled = False
                    cRowMenu.Items("mnuCut").Enabled = False
                Else
                    '    cRowMenu.Items("mnuAddNewInvestor").Enabled = True
                    '    cRowMenu.Items("mnuAddNewFund").Enabled = True
                    '    cRowMenu.Items("mnuChangedFund").Enabled = True
                    cRowMenu.Items("mnuRowEdit").Enabled = True
                    '    cRowMenu.Items("mnuCut").Enabled = True
                End If
                ''''''''''''''Starts:Row level menu items''''''''''
                'To show the row level menu items
            ElseIf grdData.Selected.Rows.Count >= 1 AndAlso row IsNot Nothing Then
                If row.Selected = False Then Exit Sub
                lblnIsFirstSelectedRow = True
                lblnCanAccessDelete = True
                lintColCounter = 0
                lblnIsSOFExists = False
                lblnIsFormulaExists = False
                lblnIsManual = False
                'ControlVisibilityRowContextMenu()
                If grdData.Selected.Rows.Count > 1 Then
                    mnuChangedFund.Enabled = False
                End If
                If grdData.Selected.Rows.Count = 1 Then
                    If row Is grdData.Selected.Rows(0) Then
                        If row.GetCellValue("IsManaged") = True Then
                            cRowMenu.Items("mnuAddNewInvestor").Enabled = False
                            cRowMenu.Items("mnuAddNewFund").Enabled = False
                            cRowMenu.Items("mnuChangedFund").Enabled = False
                            cRowMenu.Items("mnuRowEdit").Enabled = False
                        Else
                            cRowMenu.Items("mnuAddNewInvestor").Enabled = True
                            cRowMenu.Items("mnuAddNewFund").Enabled = True
                            cRowMenu.Items("mnuChangedFund").Enabled = True
                            cRowMenu.Items("mnuRowEdit").Enabled = True
                        End If
                        If row.GetCellValue("LinkID") Is DBNull.Value Then
                            cRowMenu.Items("mnuChangedFund").Enabled = False
                        ElseIf row.GetCellValue("LinkID").ToString = "0" Or row.GetCellValue("LinkID").ToString.Equals(String.Empty) Then
                            cRowMenu.Items("mnuChangedFund").Enabled = False
                        End If
                    End If
                End If
                For Each lUltraRow As UltraGridRow In grdData.Selected.Rows
                    'For Cut operation, all the selected rows must be Funds
                    'Check if the row is an Investor or a Fund
                    If lblnIsFirstSelectedRow Then
                        lintGetFirstLinkID = lUltraRow.GetCellValue("LinkID")
                    End If

                    If lintGetFirstLinkID = 0 Then
                        cRowMenu.Items("mnuCut").Enabled = False
                    Else
                        cRowMenu.Items("mnuCut").Enabled = True
                    End If

                    'If there is any cut row then enable the Insert menu item
                    If marrCutRows IsNot Nothing Then
                        If marrCutRows.Count >= 1 AndAlso marrCutRows(0) IsNot Nothing Then
                            cRowMenu.Items("mnuInsert").Enabled = True
                        Else
                            cRowMenu.Items("mnuInsert").Enabled = False
                        End If
                    End If
                    '''''''''''''''''''''''''''''''''''Starts: Functionality to provide/restrict access to Delete Row'''''''''''''''''''''''''''''''''''''''''''''''''
                    'If there is any valid value, then keep Delete menu item disabled
                    If lUltraRow.GetCellValue("IsManaged") = True Then
                        lblnCanAccessDelete = False
                        Exit For
                    End If
                    If menmScreenType = DataHubScreenType.DataEntry Then
                        CheckInvalidValue(lUltraRow, False, "", lblnCanAccessDelete)
                        If lblnCanAccessDelete = False Then Exit For
                    End If
                    'For Delete operation, either all selected rows must be Investor or Funds. 
                    'If it's an Investor row, traverse for it and associated fund and check If there is any valid value, then keep Delete menu item disabled
                    If lintGetFirstLinkID = 0 Then
                        lintLastIndexToCheck = lUltraRow.Index + 1
                        While lintLastIndexToCheck < grdData.Rows.Count
                            If grdData.Rows(lintLastIndexToCheck).GetCellValue("LinkID") = 0 Then Exit While
                            If menmScreenType = DataHubScreenType.DataEntry Then
                                CheckInvalidValue(grdData.Rows(lintLastIndexToCheck), False, "", lblnCanAccessDelete)
                                If lblnCanAccessDelete = False Then Exit For
                            End If
                            lintLastIndexToCheck += 1
                        End While
                    End If
                    'Don't move forward from here for the first row
                    If lblnIsFirstSelectedRow Then
                        lblnIsFirstSelectedRow = False
                        Continue For
                    End If
                    'Check if the first selected row is an Investor and the current traversing row is a Fund, then disable Delete
                    If lintGetFirstLinkID = 0 Then
                        If lUltraRow.GetCellValue("LinkID") <> 0 Then
                            lblnCanAccessDelete = False
                            Exit For
                        End If
                    Else
                        'Check if the first selected row is a Fudn and the current traversing row is a Fund, then disable Delete
                        If lUltraRow.GetCellValue("LinkID") = 0 Then
                            lblnCanAccessDelete = False
                            Exit For
                        End If
                    End If
                    '''''''''''''''''''''''''''''''''''Ends: Functionality to provide/restrict access to Delete Row'''''''''''''''''''''''''''''''''''''''''''''''''
                Next

                'Set the Delete menu item access
                lblnCanAccessDelete = True
                If lblnCanAccessDelete = False Then
                    cRowMenu.Items("mnuRowDelete").Enabled = False
                Else
                    cRowMenu.Items("mnuRowDelete").Enabled = Not mclsDataHubManager.GetEntityLockStatus(mintProjectID)
                End If
                'cRowMenu.Items("mnuRowDelete").Enabled = True
                cRowMenu.Show(grdData, mousePoint)
                ''''''''''''''End:Row level menu items''''''''''
                ''''''''''''''Starts:Column level menu items''''''''''
            ElseIf lcolSelectedColumn IsNot Nothing Then
                'Control the visiblity of Change Fund menu item which should be enabled when a cell is active
                ControlVisibilityRowContextMenu()
                '''''''''''''''''''''''''''''''''''Starts: Functionality to provide/restrict access to Lock/Unlock'''''''''''''''''''''''''''''''''''''''''''''''''
                'If lcolSelectedColumn.Index <= mintParentIndex OrElse marrPreviousDataSourceNameCols.Contains(lcolSelectedColumn.Header.Caption) OrElse marrPreviousSourceDateCols.Contains(lcolSelectedColumn.Header.Caption) Then Exit Sub
                lblnIsLockMenu = True
                lblnCanShowLock = True
                lblnCanShowUnLock = False
                lblnCanHideVisible = True
                lblnCanShowRetrieve = False
                lblnCanLoadMappingVisible = True
                lblnCanAddNewVisible = True
                lblnIsLockedSourceName = False
                lblnIsLockedSourceDate = False
                lblnCanShowDeleteColumn = False
                lblnCanShowCarryForward = False
                'Handle Lock Unlock menu items
                'If there are one or more selected columns
                If grdData.Selected.Columns.Count <= 1 Then
                    'Lock/Unlock/LoadMapping:If the selected column index is less that parent, then lock, unlock and Load Mapping can't be accessed
                    If lcolSelectedColumn.Index <= mintParentIndex Then
                        lblnCanShowLock = False
                        lblnCanLoadMappingVisible = False
                    Else
                        'For Carry Forward, Check if there is any Non-UPDATE locked column, if yes check if the currently selected column is a Previous Data Source
                        Dim literal As String = String.Empty
                        Dim substring As String = String.Empty
                        If grdData.Selected.Columns.Count = 1 Then
                            lobjData = mstCurrentDataSources.Find(Function(p) p.AccessStatus = SourceAccessbility.Locked.ToString)
                            If lobjData IsNot Nothing Then
                                lobjPreviousData = mstPreviousDataSources.Find(Function(p) p.SourceName = lcolSelectedColumn.Header.Caption)
                                If lobjPreviousData IsNot Nothing Then
                                    literal = lobjPreviousData.SourceName
                                    substring = literal.Substring(11, literal.Length - 11)

                                    If lobjData.ListingName = lobjPreviousData.ListingName AndAlso lobjData.SourceTypeCode = lobjData.SourceTypeCode _
                                            AndAlso lobjData.ESourceName = lobjData.ESourceName AndAlso grdData.Rows.Band.Columns.Exists(lobjData.SourceName) _
                                            AndAlso lobjData.SourceName = substring Then
                                        lblnCanShowCarryForward = True
                                        'lblnIsLockMenu = False
                                    End If
                                End If
                            End If
                        End If
                        'Otherwise, check if the selected column is Data Source or Date column
                        lobjData = Nothing
                        lobjData = mstCurrentDataSources.Find(Function(p) p.SourceName = lcolSelectedColumn.Header.Caption)
                        If lobjData Is Nothing Then
                            lobjData = mstCurrentDataSources.Find(Function(p) p.SourceDate = lcolSelectedColumn.Header.Caption)
                        End If
                        'Lock/Unlock/LoadMapping:If the selected column index is less that parent, then lock, unlock and Load Mapping can't be accessed
                        If lobjData Is Nothing Then
                            lblnCanShowLock = False
                            lblnCanLoadMappingVisible = False
                            lblnCanAddNewVisible = False
                        Else
                            'If the currently selected data source is locked, it mean Unlock column menu needs to be shown
                            lstrDataEntityColName = lobjData.SourceName
                            If lobjData.AccessStatus = SourceAccessbility.Locked.ToString Then
                                lblnIsLockMenu = False
                            End If
                            'Lock/Unlock:If the currently selected column is an eSource then Lock/Unlock menu item will be disabled
                            If lobjData.SourceTypeCode = SourceTypeCode.PBC.ToString OrElse lobjData.SourceTypeCode = SourceTypeCode.REG.ToString OrElse _
                                lobjData.SourceTypeCode = SourceTypeCode.EBL.ToString OrElse lobjData.SourceTypeCode = SourceTypeCode.EPB.ToString OrElse lobjData.ESourceCode = DataSourceCode.EDDALOT.ToString Then
                                lblnCanShowLock = False
                            End If
                            'Lock/Unlock:If the column is not a editable one, then Lock/Unlock will be disabled
                            If lblnCanShowLock Then
                                If mstEditableDataSourceNameCols.Contains(lstrDataEntityColName) Then
                                    If lobjData.AccessStatus = SourceAccessbility.Locked.ToString Then
                                        lblnCanShowLock = False
                                    End If
                                End If
                            End If
                            If mstEditableDataSourceNameCols.Contains(lstrDataEntityColName) Then
                                If lobjData.AccessStatus = SourceAccessbility.Locked.ToString Then
                                    lblnCanShowUnLock = True
                                End If
                            End If
                        End If
                    End If
                    'LoadMapping: If the selected source is not an eSource then, disable LoadMapping
                    If lobjData IsNot Nothing Then
                        If lobjData.SourceTypeCode <> SourceTypeCode.PBC.ToString AndAlso lobjData.SourceTypeCode <> SourceTypeCode.REG.ToString AndAlso _
                            lobjData.SourceTypeCode <> SourceTypeCode.EBL.ToString AndAlso lobjData.SourceTypeCode <> SourceTypeCode.EPB.ToString Then
                            lblnCanLoadMappingVisible = False
                        End If
                    End If
                    'Lock/Unlock/LoadMapping:Otherwise, if multiple columns are selected, hide Lock, Unlock and Load Mapping
                Else
                    lblnCanShowLock = False
                    lblnCanLoadMappingVisible = False
                End If

                ''''''''''''Starts:Handle Delete menu item''''''''''''''''''''''
                If grdData.Selected.Columns.Count > 0 Then
                    'Disable Delete Column if DD Questions OR DD Client Emails is selected OR If multiple columns are selected but there Source Name is different, in case of Updates
                    'If marrEditableDataSourceNameCols.Contains(
                    If menmScreenType = DataHubScreenType.DataEntry Then
                        For Each lCol As ColumnHeader In grdData.Selected.Columns
                            lstrColName = lCol.Caption
                            If mstAllDataSourceNameCols.Contains(lstrColName) = False AndAlso mstAllDataSourceDateCols.Contains(lstrColName) = False Then Continue For
                            lobjCurrentDataSources = mstCurrentDataSources.Find(Function(p) p.SourceName = lstrColName)
                            If lobjCurrentDataSources Is Nothing Then
                                lobjCurrentDataSources = mstCurrentDataSources.Find(Function(p) p.SourceDate = lstrColName)
                            End If
                            If lobjCurrentDataSources IsNot Nothing Then
                                If (lobjCurrentDataSources.AccessStatus = SourceAccessbility.Locked.ToString AndAlso _
                                    lobjCurrentDataSources.ESourceCode <> DataSourceCode.DDCLEML.ToString AndAlso _
                                    lobjCurrentDataSources.ESourceCode <> DataSourceCode.DDQUEST.ToString) Then
                                    lblnIsLockMenu = False
                                    lblnCanShowDeleteColumn = True
                                ElseIf mstESourceType.Contains(lobjCurrentDataSources.SourceTypeCode) Then
                                    lblnIsLockMenu = True
                                    lblnCanShowDeleteColumn = True
                                End If
                            End If
                        Next
                    Else
                        For Each lCol As ColumnHeader In grdData.Selected.Columns
                            lstrColName = lCol.Caption
                            If mstAllDataSourceNameCols.Contains(lstrColName) = False AndAlso mstAllDataSourceDateCols.Contains(lstrColName) = False Then
                                lblnCanShowDeleteColumn = False
                                Exit For
                            End If
                            lobjCurrentDataSources = mstCurrentDataSources.Find(Function(p) p.SourceName = lstrColName)
                            If lobjCurrentDataSources Is Nothing Then
                                lobjCurrentDataSources = mstCurrentDataSources.Find(Function(p) p.SourceDate = lstrColName)
                            End If
                            If lobjCurrentDataSources IsNot Nothing Then
                                If lobjCurrentDataSources.ESourceCode <> DataSourceCode.DDCLEML.ToString AndAlso _
                                    lobjCurrentDataSources.ESourceCode <> DataSourceCode.DDQUEST.ToString Then
                                    lblnIsLockMenu = False
                                    lblnCanShowDeleteColumn = True
                                Else
                                    lblnCanShowDeleteColumn = False
                                    Exit For
                                End If
                            End If
                        Next
                    End If
                End If
                ''''''''''''Ends:Handle Delete menu item''''''''''''''''''''''

                'Handle Hide/Unhide menu items
                'Hide: If there is not selected column or if the Name column is selected then disable the Hide menu item
                If grdData.Selected.Columns.Count = 0 OrElse lcolSelectedColumn.Header.Caption.Equals("Name") Then
                    lblnCanHideVisible = False
                    lblnCanShowRetrieve = False
                Else
                    'Hide: If there are multiple selected columns then check if any of them is locked, If so, disable Hide menu item
                    For Each lCol As ColumnHeader In grdData.Selected.Columns
                        lstrColumnName = lCol.Caption
                        lobjData = mstCurrentDataSources.Find(Function(p) p.SourceName = lstrColumnName)
                        If lobjData Is Nothing Then
                            lobjPreviousProjects = mstPreviousProjects.Find(Function(p) p.DeliveryListing = lstrColumnName)
                            If lobjPreviousProjects IsNot Nothing Then
                                lblnCanShowRetrieve = True
                                'First three previous projects cannot be hideen
                                If lobjPreviousProjects.DeliveryDateDescRank <= 3 Then
                                    lblnCanHideVisible = False
                                    Exit For
                                End If
                            End If
                        Else
                            If lobjData.AccessStatus = SourceAccessbility.Locked.ToString Then
                                lblnCanHideVisible = False
                                Exit For
                            End If
                        End If
                    Next
                End If

                'If the Lock menu to be shown
                If lblnIsLockMenu Then
                    cColLockMenu.Show(grdData, mousePoint)
                    If lblnCanAddNewVisible Then
                        cColLockMenu.Items("mnuAddNewColumn").Enabled = True
                    Else
                        cColLockMenu.Items("mnuAddNewColumn").Enabled = False
                    End If

                    'Set the Hide menu item visibility
                    If lblnCanHideVisible Then
                        cColLockMenu.Items("mnuHide").Enabled = True
                    Else
                        cColLockMenu.Items("mnuHide").Enabled = False
                    End If

                    'Set the Retrieve menu item visibility
                    If menmScreenType = DataHubScreenType.DataEntry Then
                        If lblnCanShowRetrieve Then
                            cColLockMenu.Items("mnuLockRetrieve").Enabled = True
                        Else
                            cColLockMenu.Items("mnuLockRetrieve").Enabled = False
                        End If
                    Else
                        cColLockMenu.Items("mnuLockRetrieve").Visible = False
                    End If

                    'Set the Lock/Unlock menu item visibility
                    If menmScreenType = DataHubScreenType.DataEntry Then
                        If lblnCanShowLock Then
                            cColLockMenu.Items("mnuLock").Enabled = True
                            cColLockMenu.Items("sepLock1").Visible = True
                        Else
                            cColLockMenu.Items("mnuLock").Enabled = False
                            cColLockMenu.Items("sepLock1").Visible = False
                        End If
                    Else
                        cColLockMenu.Items("mnuLock").Visible = False
                        cColLockMenu.Items("sepLock1").Visible = False
                    End If
                    'Set the Load Mapping menu item visibility
                    If lblnCanLoadMappingVisible Then
                        cColLockMenu.Items("mnuLoadMapping").Enabled = True
                    Else
                        cColLockMenu.Items("mnuLoadMapping").Enabled = False
                    End If

                    If lblnCanShowDeleteColumn Then
                        cColLockMenu.Items("mnuLockDelete").Enabled = True
                    Else
                        cColLockMenu.Items("mnuLockDelete").Enabled = False
                    End If

                    'If the UnLock menu to be shown

                    If menmScreenType = DataHubScreenType.DataEntry Then
                        If lblnCanShowCarryForward Then
                            cColLockMenu.Items("mnuCarryForward").Enabled = True
                        Else
                            cColLockMenu.Items("mnuCarryForward").Enabled = False
                        End If
                    Else
                        cColLockMenu.Items("mnuCarryForward").Visible = False
                    End If
                    'Set the Carry Forward menu item visibility
                    'lobjPreviousDataSources = mstPreviousDataSources.Find(Function(p) p.SourceName = lcolSelectedColumn.Header.Caption)
                    'If lobjPreviousDataSources IsNot Nothing Then
                    '    If menmScreenType = DataHubScreenType.FinalizeList Then
                    '        cColLockMenu.Items("mnuCarryForward").Visible = False
                    '    Else
                    '        'If marrPreviousProjects.Contains(lcolSelectedColumn.Header.Caption) Then
                    '        lobjData = mstCurrentDataSources.Find(Function(p) p.AccessStatus = SourceAccessbility.Locked.ToString)
                    '        If lobjData IsNot Nothing Then
                    '            cColLockMenu.Items("mnuCarryForward").Enabled = True
                    '        Else
                    '            cColLockMenu.Items("mnuCarryForward").Enabled = False
                    '        End If
                    '    End If
                    'Else
                    '    cColLockMenu.Items("mnuCarryForward").Enabled = False
                    'End If
                Else
                    cColUnlockMenu.Show(grdData, mousePoint)
                    'Set the Retrieve menu item visibility
                    If menmScreenType = DataHubScreenType.DataEntry Then
                        If lblnCanShowRetrieve Then
                            cColUnlockMenu.Items("mnuUnlockRetrieve").Enabled = True
                        Else
                            cColUnlockMenu.Items("mnuUnlockRetrieve").Enabled = False
                        End If
                    Else
                        cColUnlockMenu.Items("mnuUnlockRetrieve").Visible = False
                    End If

                    'Set the Carry Forward menu item visibility
                    'If menmScreenType = DataHubScreenType.DataEntry Then
                    '    If lblnCanShowCarryForward Then
                    '        cColUnlockMenu.Items("mnuCarryForward").Enabled = True
                    '    Else
                    '        cColUnlockMenu.Items("mnuCarryForward").Enabled = False
                    '    End If
                    'Else
                    '    cColUnlockMenu.Items("mnuCarryForward").Visible = False
                    'End If

                    'Set the Lock/Unlock menu item visibility
                    If menmScreenType = DataHubScreenType.DataEntry Then
                        If lblnCanShowUnLock Then
                            cColUnlockMenu.Items("mnuUnlock").Enabled = True
                            cColUnlockMenu.Items("sepUnLock1").Visible = True
                        Else
                            cColUnlockMenu.Items("mnuUnlock").Enabled = False
                            cColUnlockMenu.Items("sepUnLock1").Visible = False
                        End If
                    Else
                        cColUnlockMenu.Items("mnuUnlock").Visible = False
                        cColUnlockMenu.Items("sepUnLock1").Visible = False
                    End If

                    If lblnCanShowDeleteColumn Then
                        cColUnlockMenu.Items("mnuDelete").Enabled = True
                    Else
                        cColUnlockMenu.Items("mnuDelete").Enabled = False
                    End If
                End If

                'If Lock/Unlock can be shown, store the current column name so that will be used for Locking purposes
                mstrRightClickColName = lcolSelectedColumn.Header.Caption
                '''''''''''''''''''''''''''''''''''Ends: Functionality to provide/restrict access to Lock/Unlock'''''''''''''''''''''''''''''''''''''''''''''''''
            End If
            ''''''''''''''Starts:Column level menu items''''''''''
        Catch ex As Exception
            Me.FormulateAndLogError(ex, Me.Text, mintProjectID)
        Finally
            el = Nothing
            lobjCurrentDataSources = Nothing
            lobjPreviousProjects = Nothing
            lobjData = Nothing
            cell = Nothing
            row = Nothing
            lcolSelectedColumn = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' Control the visiblity of Changed Fund menu item
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ControlVisibilityRowContextMenu()
        'If the active cell is not nothing, hide others and just show Change Fund
        If grdData.ActiveCell IsNot Nothing Then
            For Each lContextMenuItem As ToolStripMenuItem In cRowMenu.Items.OfType(Of ToolStripMenuItem)()
                If lContextMenuItem IsNot mnuChangedFund AndAlso lContextMenuItem IsNot mnuRowEdit Then
                    lContextMenuItem.Enabled = False
                End If
                If grdData.ActiveCell.Row.GetCellValue("LinkID") Is DBNull.Value Then
                    cRowMenu.Items("mnuChangedFund").Enabled = False
                ElseIf grdData.ActiveCell.Row.GetCellValue("LinkID").ToString = "0" Or grdData.ActiveCell.Row.GetCellValue("LinkID").ToString.Equals(String.Empty) Then
                    cRowMenu.Items("mnuChangedFund").Enabled = False
                Else
                    cRowMenu.Items("mnuChangedFund").Enabled = True
                End If
            Next
        Else
            'If the active cell is nothing, then show Change Fund
            mnuChangedFund.Enabled = True
            mnuRowEdit.Enabled = True
        End If
    End Sub

    ''' <summary>
    ''' To ReEnable the data hub screen after coming from eSource Mapping screen
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ReEnableDataHub(ByVal pblnIsImportSuccessful As Boolean)
        If pblnIsImportSuccessful Then
            ConductRecallDataChanges(mstCurrentDataSources, Nothing, False, grdData.DataSource, RecallChangesCaller.ReEnableDataHub)
        End If
        spcDataHub.Enabled = True
    End Sub

    ''' <summary>
    ''' Set the default text
    ''' </summary>
    ''' <param name="txtText"></param>
    ''' <remarks></remarks>
    Public Sub SetDefaulSearchText(ByVal txtText As TextBox)
        txtText.Text = MessageManager.GetMessage("DEFAULTSEARCHTEXT")
    End Sub

    ''' <summary>
    ''' Make the cell value hyperlink if the value is url. i.e. website address.
    ''' </summary>
    ''' <param name="_websiteAddress"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ValidatewebsiteAddress(ByVal _websiteAddress As String) As Boolean
        If Not Regex.IsMatch(_websiteAddress, _
       "^((ht|f)tp(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.[\w]{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?") Then
            Return False
        Else
            Return True
        End If
    End Function

    ''' <summary>
    ''' To mark an Investor/Fund delete
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub MarkEntityDelete(ByVal lUltraRow As UltraGridRow)
        lUltraRow.Cells("Name").Appearance.BackColor = mclrDelAndExtnct
        lUltraRow.Cells("InvStatusCode").Value = EntityStatus.DELTE.ToString
        lUltraRow.Cells("Status").Value = EntityStatusName.Delete.ToString
    End Sub

    Private Sub GetVisibleColumnsFL(ByRef lstVisibleColumns As List(Of String))
        If grdData.DataSource IsNot Nothing Then
            For Each col As UltraGridColumn In grdData.DisplayLayout.Bands(0).Columns
                If col.Hidden = False Then
                    lstVisibleColumns.Add(col.Header.Caption.ToString)
                End If
            Next
        End If
    End Sub

#End Region

#Region "General"

    ''' <summary>
    ''' Find the index of corresponding Investor row by passing an ultragrid row
    ''' </summary>
    ''' <param name="lintActiveRowIndex"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function FindInvestorIndex(ByVal lintActiveRowIndex As Integer) As Integer
        Dim lintRowCounter As Integer = lintActiveRowIndex
        Dim lintInvestorRowIndex As Integer
        While lintRowCounter > 0
            If grdData.Rows(lintRowCounter).GetCellValue("LinkID") = 0 Then
                lintInvestorRowIndex = lintRowCounter
                Exit While
            End If
            lintRowCounter -= 1
        End While
        Return lintInvestorRowIndex
    End Function

    ''' <summary>
    ''' Find the index of Next Investor row by passing an ultragrid row
    ''' </summary>
    ''' <param name="lintActiveRowIndex"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function FindNextInvestorIndex(ByVal lintActiveRowIndex As Integer) As Integer
        Dim lintRowCounter As Integer = lintActiveRowIndex
        Dim lintInvestorRowIndex As Integer
        While lintRowCounter < grdData.Rows.Count
            If grdData.Rows(lintRowCounter).GetCellValue("LinkID") = 0 Then
                lintInvestorRowIndex = lintRowCounter
                Exit While
            End If
            lintRowCounter += 1
        End While
        Return lintInvestorRowIndex
    End Function

    ''' <summary>
    ''' Pass the InvestorId and InvestorName where the new fund 'll add.
    ''' </summary>
    ''' <param name="intInvestorID"></param>
    ''' <param name="strInvestorName"></param>
    ''' <remarks></remarks>
    Private Sub GetInvestorID(ByRef intInvestorID As Integer, ByRef strInvestorName As String)
        Dim lintIndex As Integer
        lintIndex = grdData.Selected.Rows(0).Index
        'Code Commented As per requirement now the new fund will be added to selected investor not to the above one.
        If lintIndex = 0 Then
            If grdData.Rows(lintIndex).GetCellValue("IsInvestor") = True Then
                intInvestorID = grdData.Rows(lintIndex).GetCellValue("InvestorID")
                strInvestorName = grdData.Rows(lintIndex).GetCellValue("Name")
                Exit Sub
            End If
            ' As per requirement now the new fund will be added to selected investor not to the above one.
        End If
        ' Make the loop until it get the investor of selected fund.
        For i As Integer = lintIndex To 0 Step -1
            If i >= 0 Then

                If grdData.Rows(i).GetCellValue("IsInvestor") = True Then
                    intInvestorID = grdData.Rows(i).GetCellValue("InvestorID")
                    strInvestorName = grdData.Rows(i).GetCellValue("Name")
                    Exit For
                End If
            End If
        Next
        'Code Commented As per requirement now the new fund will be added to selected investor not to the above one.
    End Sub
#End Region
#End Region

#Region "Test"

    Private Sub grdData_BeforeRowRegionScroll(ByVal sender As Object, ByVal e As Infragistics.Win.UltraWinGrid.BeforeRowRegionScrollEventArgs) Handles grdData.BeforeRowRegionScroll
        'ConsiderPositionData(e.NewState.VisibleRows, grdData.DisplayLayout.ColScrollRegions(0).VisibleHeaders)
    End Sub

#End Region

End Class